home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / PRG / PL 2.0 SupplementDoc Folder.sit / PL 2.0 SupplementDoc Folder / Documentation / Chapter 07. Control Structure < prev    next >
Text File  |  1995-03-27  |  175KB  |  4,007 lines

  1. Common Lisp the Language, 2nd Edition
  2. -------------------------------------------------------------------------------
  3.  
  4. 7. Control Structure
  5.  
  6. Common Lisp provides a variety of special structures for organizing programs.
  7. Some have to do with flow of control (control structures), while others control
  8. access to variables (environment structures). Some of these features are
  9. implemented as special forms; others are implemented as macros, which typically
  10. expand into complex program fragments expressed in terms of special forms or
  11. other macros.
  12.  
  13. Function application is the primary method for construction of Lisp programs.
  14. Operations are written as the application of a function to its arguments.
  15. Usually, Lisp programs are written as a large collection of small functions,
  16. each of which implements a simple operation. These functions operate by calling
  17. one another, and so larger operations are defined in terms of smaller ones.
  18. Lisp functions may call upon themselves recursively, either directly or
  19. indirectly.
  20.  
  21. [change_begin]
  22. Locally defined functions (flet, labels) and macros (macrolet) are quite
  23. versatile. The new symbol macro facility allows even more syntactic
  24. flexibility.
  25. [change_end]
  26.  
  27. While the Lisp language is more applicative in style than statement-oriented,
  28. it nevertheless provides many operations that produce side effects and
  29. consequently requires constructs for controlling the sequencing of side
  30. effects. The construct progn, which is roughly equivalent to an Algol begin-end
  31. block with all its semicolons, executes a number of forms sequentially,
  32. discarding the values of all but the last. Many Lisp control constructs include
  33. sequencing implicitly, in which case they are said to provide an ``implicit
  34. progn.''   Other sequencing constructs include prog1 and prog2.
  35.  
  36. For looping, Common Lisp provides the general iteration facility do as well as
  37. a variety of special-purpose iteration facilities for iterating or mapping over
  38. various data structures.
  39.  
  40. Common Lisp provides the simple one-way conditionals when and unless, the
  41. simple two-way conditional if, and the more general multi-way conditionals such
  42. as cond and case. The choice of which form to use in any particular situation
  43. is a matter of taste and style.
  44.  
  45. Constructs for performing non-local exits with various scoping disciplines are
  46. provided: block, return, return-from, catch, and throw.
  47.  
  48. The multiple-value constructs provide an efficient way for a function to return
  49. more than one value; see values.
  50.  
  51. -------------------------------------------------------------------------------
  52.  
  53.    *  Constants and Variables
  54.         o  Reference
  55.         o  Assignment
  56.    *  Generalized Variables
  57.    *  Function Invocation
  58.    *  Simple Sequencing
  59.    *  Establishing New Variable Bindings
  60.    *  Conditionals
  61.    *  Blocks and Exits
  62.    *  Iteration
  63.         o  Indefinite Iteration
  64.         o  General Iteration
  65.         o  Simple Iteration Constructs
  66.         o  Mapping
  67.         o  The ``Program Feature''
  68.    *  Structure Traversal and Side Effects
  69.    *  Multiple Values
  70.         o  Constructs for Handling Multiple Values
  71.         o  Rules Governing the Passing of Multiple Values
  72.    *  Dynamic Non-Local Exits
  73.  
  74. -------------------------------------------------------------------------------
  75.  
  76. 7.1. Constants and Variables
  77.  
  78. Because some Lisp data objects are used to represent programs, one cannot
  79. always notate a constant data object in a program simply by writing the
  80. notation for the object unadorned; it would be ambiguous whether a constant
  81. object or a program fragment was intended. The quote special form resolves this
  82. ambiguity.
  83.  
  84. There are two kinds of variables in Common Lisp, in effect: ordinary variables
  85. and function names. There are some similarities between the two kinds, and in a
  86. few cases there are similar functions for dealing with them, for example boundp
  87. and fboundp. However, for the most part the two kinds of variables are used for
  88. very different purposes: one to name defined functions, macros, and special
  89. forms, and the other to name data objects.
  90.  
  91. [change_begin]
  92. X3J13 voted in March 1989 (FUNCTION-NAME)   to introduce the concept of a
  93. function-name, which may be either a symbol or a two-element list whose first
  94. element is the symbol setf and whose second element is a symbol. The primary
  95. purpose of this is to allow setf expander functions to be CLOS generic
  96. functions with user-defined methods. Many places in Common Lisp that used to
  97. require a symbol for a function name are changed to allow 2-lists as well; for
  98. example, defun is changed so that one may write (defun (setf foo) ...), and the
  99. function special form is changed to accept any function-name. See also
  100. fdefinition.
  101.  
  102. By convention, any function named (setf f) should return its first argument as
  103. its only value, in order to preserve the specification that setf returns its
  104. newvalue. See setf.
  105.  
  106. Implementations are free to extend the syntax of function-names to include
  107. lists beginning with additional symbols other than setf or lambda.
  108. [change_end]
  109.  
  110. -------------------------------------------------------------------------------
  111.  
  112.    *  Reference
  113.    *  Assignment
  114.  
  115. -------------------------------------------------------------------------------
  116.  
  117. 7.1. Reference
  118.  
  119. The value of an ordinary variable may be obtained simply by writing the name of
  120. the variable as a form to be executed. Whether this is treated as the name of a
  121. special variable or a lexical variable is determined by the presence or absence
  122. of an applicable special declaration; see chapter 9.
  123.  
  124. The following functions and special forms allow reference to the values of
  125. constants and variables in other ways.
  126.  
  127. [Special Form]
  128. quote object
  129.  
  130. (quote x) simply returns x. The object is not evaluated and may be any Lisp
  131. object whatsoever. This construct allows any Lisp object to be written as a
  132. constant value in a program. For example:
  133.  
  134. (setq a 43)
  135. (list a (cons a 3)) => (43 (43 . 3))
  136. (list (quote a) (quote (cons a 3)) => (a (cons a 3))
  137.  
  138. Since quote forms are so frequently useful but somewhat cumbersome to type, a
  139. standard abbreviation is defined for them: any form f preceded by a single
  140. quote (') character is assumed to have (quote ) wrapped around it to make
  141. (quote f). For example:
  142.  
  143. (setq x '(the magic quote hack))
  144.  
  145. is normally interpreted by read to mean
  146.  
  147. (setq x (quote (the magic quote hack)))
  148.  
  149. See section 22.1.3.
  150.  
  151. [change_begin]
  152. X3J13 voted in January 1989 (CONSTANT-MODIFICATION)   to clarify that it is an
  153. error to destructively modify any object that appears as a constant in
  154. executable code, whether within a quote special form or as a self-evaluating
  155. form.
  156.  
  157. See section 25.1 for a discussion of how quoted constants are treated by the
  158. compiler.
  159.  
  160. X3J13 voted in March 1989 (QUOTE-SEMANTICS)   to clarify that eval and compile
  161. are not permitted either to copy or to coalesce (``collapse'') constants (see
  162. eq) appearing in the code they process; the resulting program behavior must
  163. refer to objects that are eql to the corresponding objects in the source code.
  164. Moreover, the constraints introduced by the votes on issues
  165. (CONSTANT-COMPILABLE-TYPES)   and (CONSTANT-CIRCULAR-COMPILATION)   on what
  166. kinds of objects may appear as constants apply only to compile-file (see
  167. section 25.1).
  168. [change_end]
  169.  
  170. [Special Form]
  171. function fn
  172.  
  173. The value of function is always the functional interpretation of fn; fn is
  174. interpreted as if it had appeared in the functional position of a function
  175. invocation. In particular, if fn is a symbol, the functional definition
  176. associated with that symbol is returned; see symbol-function. If fn is a
  177. lambda-expression, then a ``lexical closure'' is returned, that is, a function
  178. that when invoked will execute the body of the lambda-expression in such a way
  179. as to observe the rules of lexical scoping properly.
  180.  
  181. [change_begin]
  182. X3J13 voted in June 1988 (FUNCTION-TYPE)   to specify that the result of a
  183. function special form is always of type function. This implies that a form
  184. (function fn) may be interpreted as (the (function fn)).
  185.  
  186. It is an error to use the function special form on a symbol that does not
  187. denote a function in the lexical or global environment in which the special
  188. form appears. Specifically, it is an error to use the function special form on
  189. a symbol that denotes a macro or special form. Some implementations may choose
  190. not to signal this error for performance reasons, but implementations are
  191. forbidden to extend the semantics of function in this respect; that is, an
  192. implementation is not allowed to define the failure to signal an error to be a
  193. ``useful'' behavior.
  194.  
  195. X3J13 voted in March 1989 (FUNCTION-NAME)   to extend function to accept any
  196. function-name (a symbol or a list whose car is setf-see section 7.1) as well as
  197. lambda-expressions. Thus one may write (function (setf cadr)) to refer to the
  198. setf expansion function for cadr.
  199. [change_end]
  200.  
  201.   For example:
  202.  
  203. (defun adder (x) (function (lambda (y) (+ x y))))
  204.  
  205. The result of (adder 3) is a function that will add 3 to its argument:
  206.  
  207. (setq add3 (adder 3))
  208. (funcall add3 5) => 8
  209.  
  210. This works because function creates a closure of the inner lambda-expression
  211. that is able to refer to the value 3 of the variable x even after control has
  212. returned from the function adder.
  213.  
  214. More generally, a lexical closure in effect retains the ability to refer to
  215. lexically visible bindings, not just values. Consider this code:
  216.  
  217. (defun two-funs (x)
  218.   (list (function (lambda () x))
  219.         (function (lambda (y) (setq x y)))))
  220. (setq funs (two-funs 6))
  221. (funcall (car funs)) => 6
  222. (funcall (cadr funs) 43) => 43
  223. (funcall (car funs)) => 43
  224.  
  225. The function two-funs returns a list of two functions, each of which refers to
  226. the binding of the variable x created on entry to the function two-funs when it
  227. was called with argument 6. This binding has the value 6 initially, but setq
  228. can alter a binding. The lexical closure created for the first
  229. lambda-expression does not ``snapshot'' the value 6 for x when the closure is
  230. created. The second function can be used to alter the binding (to 43, in the
  231. example), and this altered value then becomes accessible to the first function.
  232.  
  233. In situations where a closure of a lambda-expression over the same set of
  234. bindings may be produced more than once, the various resulting closures may or
  235. may not be eq, at the discretion of the implementation. For example:
  236.  
  237. (let ((x 5) (funs '()))
  238.   (dotimes (j 10)
  239.     (push #'(lambda (z)
  240.               (if (null z) (setq x 0) (+ x z)))
  241.           funs))
  242.   funs)
  243.  
  244. The result of the above expression is a list of ten closures. Each logically
  245. requires only the binding of x. It is the same binding in each case, so the ten
  246. closures may or may not be the same identical (eq) object. On the other hand,
  247. the result of the expression
  248.  
  249. (let ((funs '()))
  250.   (dotimes (j 10)
  251.     (let ((x 5))
  252.       (push (function (lambda (z)
  253.                         (if (null z) (setq x 0) (+ x z))))
  254.             funs)))
  255.   funs)
  256.  
  257. is also a list of ten closures. However, in this case no two of the closures
  258. may be eq, because each closure is over a distinct binding of x, and these
  259. bindings can be behaviorally distinguished because of the use of setq.
  260.  
  261. The question of distinguishable behavior is important; the result of the
  262. simpler expression
  263.  
  264. (let ((funs '()))
  265.   (dotimes (j 10)
  266.     (let ((x 5))
  267.       (push (function (lambda (z) (+ x z)))
  268.             funs)))
  269.   funs)
  270.  
  271. is a list of ten closures that may be pairwise eq. Although one might think
  272. that a different binding of x is involved for each closure (which is indeed the
  273. case), the bindings cannot be distinguished because their values are identical
  274. and immutable, there being no occurrence of setq on x. A compiler would
  275. therefore be justified in transforming the expression to
  276.  
  277. (let ((funs '()))
  278.   (dotimes (j 10)
  279.     (push (function (lambda (z) (+ 5 z)))
  280.           funs))
  281.   funs)
  282.  
  283. where clearly the closures may be the same after all. The general rule, then,
  284. is that the implementation is free to have two distinct evaluations of the same
  285. function form produce identical (eq) closures if it can prove that the two
  286. conceptually distinct resulting closures must in fact be behaviorally identical
  287. with respect to invocation. This is merely a permitted optimization; a
  288. perfectly valid implementation might simply cause every distinct evaluation of
  289. a function form to produce a new closure object not eq to any other.
  290.  
  291. Frequently a compiler can deduce that a closure in fact does not need to close
  292. over any variable bindings. For example, in the code fragment
  293.  
  294. (mapcar (function (lambda (x) (+ x 2))) y)
  295.  
  296. the function (lambda (x) (+ x 2)) contains no references to any outside entity.
  297. In this important special case, the same ``closure'' may be used as the value
  298. for all evaluations of the function special form. Indeed, this value need not
  299. be a closure object at all; it may be a simple compiled function containing no
  300. environment information. This example is simply a special case of the foregoing
  301. discussion and is included as a hint to implementors familiar with previous
  302. methods of implementing Lisp. The distinction between closures and other kinds
  303. of functions is somewhat pointless, actually, as Common Lisp defines no
  304. particular representation for closures and no way to distinguish between
  305. closures and non-closure functions. All that matters is that the rules of
  306. lexical scoping be obeyed.
  307.  
  308. Since function forms are so frequently useful but somewhat cumbersome to type,
  309. a standard abbreviation is defined for them: any form f preceded by #' (#
  310. followed by an apostrophe) is assumed to have (function ) wrapped around it to
  311. make (function f). For example,
  312.  
  313. (remove-if #'numberp '(1 a b 3))
  314.  
  315. is normally interpreted by read to mean
  316.  
  317. (remove-if (function numberp) '(1 a b 3))
  318.  
  319. See section 22.1.4.
  320.  
  321. [Function]
  322. symbol-value symbol
  323.  
  324. symbol-value returns the current value of the dynamic (special) variable named
  325. by symbol. An error occurs if the symbol has no value; see boundp and
  326. makunbound. Note that constant symbols are really variables that cannot be
  327. changed, and so symbol-value may be used to get the value of a named constant.
  328. In particular, symbol-value of a keyword will return that keyword.
  329.  
  330. symbol-value cannot access the value of a lexical variable.
  331.  
  332. This function is particularly useful for implementing interpreters for
  333. languages embedded in Lisp. The corresponding assignment primitive is set;
  334. alternatively, symbol-value may be used with setf.
  335.  
  336. [Function]
  337. symbol-function symbol
  338.  
  339. symbol-function returns the current global function definition named by symbol.
  340. An error is signalled if the symbol has no function definition; see fboundp.
  341. Note that the definition may be a function or may be an object representing a
  342. special form or macro. In the latter case, however, it is an error to attempt
  343. to invoke the object as a function. If it is desired to process macros, special
  344. forms, and functions equally well, as when writing an interpreter, it is best
  345. first to test the symbol with macro-function and special-form-p and then to
  346. invoke the functional value only if these two tests both yield false.
  347.  
  348. This function is particularly useful for implementing interpreters for
  349. languages embedded in Lisp.
  350.  
  351. symbol-function cannot access the value of a lexical function name produced by
  352. flet or labels; it can access only the global function value.
  353.  
  354. The global function definition of a symbol may be altered by using setf with
  355. symbol-function. Performing this operation causes the symbol to have only the
  356. specified definition as its global function definition; any previous
  357. definition, whether as a macro or as a function, is lost. It is an error to
  358. attempt to redefine the name of a special form (see table 5-1).
  359.  
  360. [change_begin]
  361. X3J13 voted in June 1988 (FUNCTION-TYPE)   to clarify the behavior of
  362. symbol-function in the light of the redefinition of the type function.
  363.  
  364.    *  It is permissible to call symbol-function on any symbol for which fboundp
  365.      returns true. Note that fboundp must return true for a symbol naming a
  366.      macro or a special form.
  367.  
  368.    *  If fboundp returns true for a symbol but the symbol denotes a macro or
  369.      special form, then the value returned by symbol-function is not
  370.      well-defined but symbol-function will not signal an error.
  371.  
  372.    *  When symbol-function is used with setf the new value must be of type
  373.      function. It is an error to set the symbol-function of a symbol to a
  374.      symbol, a list, or the value returned by symbol-function on the name of a
  375.      macro or a special form.
  376.  
  377. [change_end]
  378.  
  379. [change_begin]
  380.  
  381. [Function]
  382. fdefinition function-name
  383.  
  384. X3J13 voted in March 1989 (FUNCTION-NAME)   to add the function fdefinition to
  385. the language. It is exactly like symbol-function except that its argument may
  386. be any function-name (a symbol or a list whose car is setf-see section 7.1); it
  387. returns the current global function definition named by the argument
  388. function-name. One may use fdefinition with setf to change the current global
  389. function definition associated with a function-name.
  390. [change_end]
  391.  
  392. [Function]
  393. boundp symbol
  394.  
  395. boundp is true if the dynamic (special) variable named by symbol has a value;
  396. otherwise, it returns nil.
  397.  
  398. See also set and makunbound.
  399.  
  400. [Function]
  401. fboundp symbol
  402.  
  403. fboundp is true if the symbol has a global function definition. Note that
  404. fboundp is true when the symbol names a special form or macro. macro-function
  405. and special-form-p may be used to test for these cases.
  406.  
  407. [change_begin]
  408. X3J13 voted in June 1988 (FUNCTION-TYPE)   to emphasize that, despite the
  409. tightening of the definition of the type function, fboundp must return true
  410. when the argument names a special form or macro.
  411.  
  412. See also symbol-function and fmakunbound.
  413.  
  414. X3J13 voted in March 1989 (FUNCTION-NAME)   to extend fboundp to accept any
  415. function-name (a symbol or a list whose car is setf-see section 7.1). Thus one
  416. may write (fboundp '(setf cadr)) to determine whether a setf expansion function
  417. has been globally defined for cadr.
  418. [change_end]
  419.  
  420. [Function]
  421. special-form-p symbol
  422.  
  423. The function special-form-p takes a symbol. If the symbol globally names a
  424. special form, then a non-nil value is returned; otherwise nil is returned. A
  425. returned non-nil value is typically a function of implementation-dependent
  426. nature that can be used to interpret (evaluate) the special form.
  427.  
  428. It is possible for both special-form-p and macro-function to be true of a
  429. symbol. This is possible because an implementation is permitted to implement
  430. any macro also as a special form for speed. On the other hand, the macro
  431. definition must be available for use by programs that understand only the
  432. standard special forms listed in table 5-1.
  433.  
  434. -------------------------------------------------------------------------------
  435.  
  436. 7.1.2. Assignment
  437.  
  438. The following facilities allow the value of a variable (more specifically, the
  439. value associated with the current binding of the variable) to be altered. Such
  440. alteration is different from establishing a new binding. Constructs for
  441. establishing new bindings of variables are described in section 7.5.
  442.  
  443. [Special Form]
  444. setq {var form}*
  445.  
  446. The special form (setq var1 form1 var2 form2 ...) is the ``simple variable
  447. assignment statement'' of Lisp. First form1 is evaluated and the result is
  448. stored in the variable var1, then form2 is evaluated and the result stored in
  449. var2, and so forth. The variables are represented as symbols, of course, and
  450. are interpreted as referring to static or dynamic instances according to the
  451. usual rules. Therefore setq may be used for assignment of both lexical and
  452. special variables.
  453.  
  454. setq returns the last value assigned, that is, the result of the evaluation of
  455. its last argument. As a boundary case, the form (setq) is legal and returns
  456. nil. There must be an even number of argument forms. For example, in
  457.  
  458. (setq x (+ 3 2 1) y (cons x nil))
  459.  
  460. x is set to 6, y is set to (6), and the setq returns (6). Note that the first
  461. assignment is performed before the second form is evaluated, allowing that form
  462. to use the new value of x.
  463.  
  464. See also the description of setf, the Common Lisp ``general assignment
  465. statement'' that is capable of assigning to variables, array elements, and
  466. other locations.
  467.  
  468. [change_begin]
  469. Some programmers choose to avoid setq as a matter of style, always using setf
  470. for any kind of structure modification. Others use setq with simple variable
  471. names and setf with all other generalized variables.
  472.  
  473. X3J13 voted in March 1989 (SYMBOL-MACROLET-SEMANTICS)   to specify that if any
  474. var refers not to an ordinary variable but to a binding made by
  475. symbol-macrolet, then that var is handled as if setf had been used instead of
  476. setq.
  477. [change_end]
  478.  
  479. [Macro]
  480. psetq {var form}*
  481.  
  482. A psetq form is just like a setq form, except that the assignments happen in
  483. parallel. First all of the forms are evaluated, and then the variables are set
  484. to the resulting values. The value of the psetq form is nil. For example:
  485.  
  486. (setq a 1)
  487. (setq b 2)
  488. (psetq a b  b a)
  489. a => 2
  490. b => 1
  491.  
  492. In this example, the values of a and b are exchanged by using parallel
  493. assignment. (If several variables are to be assigned in parallel in the context
  494. of a loop, the do construct may be appropriate.)
  495.  
  496. See also the description of psetf, the Common Lisp ``general parallel
  497. assignment statement'' that is capable of assigning to variables, array
  498. elements, and other locations.
  499.  
  500. [change_begin]
  501. X3J13 voted in March 1989 (SYMBOL-MACROLET-SEMANTICS)   to specify that if any
  502. var refers not to an ordinary variable but to a binding made by
  503. symbol-macrolet, then that var is handled as if psetf had been used instead of
  504. psetq.
  505. [change_end]
  506.  
  507. [Function]
  508. set symbol value
  509.  
  510. set allows alteration of the value of a dynamic (special) variable. set causes
  511. the dynamic variable named by symbol to take on value as its value.
  512.  
  513. [change_begin]
  514. X3J13 voted in January 1989 (ARGUMENTS-UNDERSPECIFIED)   to clarify that the
  515. value may be any Lisp datum whatsoever.
  516. [change_end]
  517.  
  518. Only the value of the current dynamic binding is altered; if there are no
  519. bindings in effect, the most global value is altered. For example,
  520.  
  521. (set (if (eq a b) 'c 'd) 'foo)
  522.  
  523. will either set c to foo or set d to foo, depending on the outcome of the test
  524. (eq a b).
  525.  
  526. set returns value as its result.
  527.  
  528. set cannot alter the value of a local (lexically bound) variable. The special
  529. form setq is usually used for altering the values of variables (lexical or
  530. dynamic) in programs. set is particularly useful for implementing interpreters
  531. for languages embedded in Lisp. See also progv, a construct that performs
  532. binding rather than assignment of dynamic variables.
  533.  
  534. [Function]
  535. makunbound symbol
  536. fmakunbound symbol
  537.  
  538. makunbound causes the dynamic (special) variable named by symbol to become
  539. unbound (have no value). fmakunbound does the analogous thing for the global
  540. function definition named by symbol. For example:
  541.  
  542. (setq a 1)
  543. a => 1
  544. (makunbound 'a)
  545. a => causes an error
  546.  
  547. (defun foo (x) (+ x 1))
  548. (foo 4) => 5
  549. (fmakunbound 'foo)
  550. (foo 4) => causes an error
  551.  
  552. Both functions return symbol as the result value.
  553.  
  554. [change_begin]
  555. X3J13 voted in March 1989 (FUNCTION-NAME)   to extend fmakunbound to accept any
  556. function-name (a symbol or a list whose car is setf - see section 7.1). Thus
  557. one may write (fmakunbound '(setf cadr)) to remove any global definition of a
  558. setf expansion function for cadr.
  559. [change_end]
  560.  
  561. -------------------------------------------------------------------------------
  562.  
  563. 7.2. Generalized Variables
  564.  
  565. In Lisp, a variable can remember one piece of data, that is, one Lisp object.
  566. The main operations on a variable are to recover that object and to alter the
  567. variable to remember a new object; these operations are often called access and
  568. update operations. The concept of variables named by symbols can be generalized
  569. to any storage location that can remember one piece of data, no matter how that
  570. location is named. Examples of such storage locations are the car and cdr of a
  571. cons, elements of an array, and components of a structure.
  572.  
  573. For each kind of generalized variable, typically there are two functions that
  574. implement the conceptual access and update operations. For a variable, merely
  575. mentioning the name of the variable accesses it, while the setq special form
  576. can be used to update it. The function car accesses the car of a cons, and the
  577. function rplaca updates it. The function symbol-value accesses the dynamic
  578. value of a variable named by a given symbol, and the function set updates it.
  579.  
  580. Rather than thinking about two distinct functions that respectively access and
  581. update a storage location somehow deduced from their arguments, we can instead
  582. simply think of a call to the access function with given arguments as a name
  583. for the storage location. Thus, just as x may be considered a name for a
  584. storage location (a variable), so (car x) is a name for the car of some cons
  585. (which is in turn named by x). Now, rather than having to remember two
  586. functions for each kind of generalized variable (having to remember, for
  587. example, that rplaca corresponds to car), we adopt a uniform syntax for
  588. updating storage locations named in this way, using the setf macro. This is
  589. analogous to the way we use the setq special form to convert the name of a
  590. variable (which is also a form that accesses it) into a form that updates it.
  591. The uniformity of this approach is illustrated in the following table.
  592.  
  593. Access Function     Update Function      Update Using setf
  594. ----------------------------------------------------------------------
  595. x                   (setq x datum)       (setf x datum)
  596. (car x)             (rplaca x datum)     (setf (car x) datum)
  597. (symbol-value x)    (set x datum)        (setf (symbol-value x) datum)
  598. ----------------------------------------------------------------------
  599.  
  600. setf is actually a macro that examines an access form and produces a call to
  601. the corresponding update function.
  602.  
  603. Given the existence of setf in Common Lisp, it is not necessary to have setq,
  604. rplaca, and set; they are redundant. They are retained in Common Lisp because
  605. of their historical importance in Lisp. However, most other update functions
  606. (such as putprop, the update function for get) have been eliminated from Common
  607. Lisp in the expectation that setf will be uniformly used in their place.
  608.  
  609. [Macro]
  610. setf {place newvalue}*
  611.  
  612. (setf place newvalue) takes a form place that when evaluated accesses a data
  613. object in some location and ``inverts'' it to produce a corresponding form to
  614. update the location. A call to the setf macro therefore expands into an update
  615. form that stores the result of evaluating the form newvalue into the place
  616. referred to by the access form.
  617.  
  618. If more than one place-newvalue pair is specified, the pairs are processed
  619. sequentially; that is,
  620.  
  621. (setf place1 newvalue1
  622.       place2 newvalue2)
  623.       ...
  624.       placen newvaluen)
  625.  
  626. is precisely equivalent to
  627.  
  628. (progn (setf place1 newvalue1)
  629.        (setf place2 newvalue2)
  630.        ...
  631.        (setf placen newvaluen))
  632.  
  633. For consistency, it is legal to write (setf), which simply returns nil.
  634.  
  635. The form place may be any one of the following:
  636.  
  637.    *  The name of a variable (either lexical or dynamic).
  638.  
  639.    *  A function call form whose first element is the name of any one of the
  640.      following functions:
  641.  
  642.      aref        car        svref
  643.      nth         cdr        get
  644.      elt         caar       getf             symbol-value
  645.      rest        cadr       gethash          symbol-function
  646.      first       cdar       documentation    symbol-plist
  647.      second      cddr       fill-pointer     macro-function
  648.      third       caaar      caaaar           cdaaar
  649.      fourth      caadr      caaadr           cdaadr
  650.      fifth       cadar      caadar           cdadar
  651.      sixth       caddr      caaddr           cdaddr
  652.      seventh     cdaar      cadaar           cddaar
  653.      eighth      cdadr      cadadr           cddadr
  654.      ninth       cddar      caddar           cdddar
  655.      tenth       cdddr      cadddr           cddddr
  656.  
  657. [change_begin]
  658.  
  659.      X3J13 voted in March 1988 (AREF-1D)   to add row-major-aref to this list.
  660.  
  661.      X3J13 voted in June 1989 (DEFINE-COMPILER-MACRO)   to add
  662.      compiler-macro-function to this list.
  663.  
  664.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  665.      applies only when the function name refers to a global function definition
  666.      and not to a locally defined function or macro.
  667.  
  668. [change_end]
  669.  
  670.    *  A function call form whose first element is the name of a selector
  671.      function constructed by defstruct.
  672.  
  673. [change_begin]
  674.  
  675.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  676.      applies only when the function name refers to a global function definition
  677.      and not to a locally defined function or macro.
  678.  
  679. [change_end]
  680.  
  681.    *  A function call form whose first element is the name of any one of the
  682.      following functions, provided that the new value is of the specified type
  683.      so that it can be used to replace the specified ``location'' (which is in
  684.      each of these cases not truly a generalized variable):
  685.  
  686.      Function Name   Required Type
  687.      --------------------------------
  688.      char    string-char
  689.      schar   string-char
  690.      bit     bit
  691.      sbit    bit
  692.      subseq  sequence
  693.      --------------------------------
  694.  
  695. [change_begin]
  696.  
  697.      X3J13 voted in March 1989 (CHARACTER-PROPOSAL)   to eliminate the type
  698.      string-char and to redefine string to be the union of one or more
  699.      specialized vector types, the types of whose elements are subtypes of the
  700.      type character. In the preceding table, the type string-char should be
  701.      replaced by some such phrase as ``the element-type of the argument
  702.      vector.''
  703.  
  704.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  705.      applies only when the function name refers to a global function definition
  706.      and not to a locally defined function or macro.
  707.  
  708. [change_end]
  709.  
  710.      In the case of subseq, the replacement value must be a sequence whose
  711.      elements may be contained by the sequence argument to subseq. (Note that
  712.      this is not so stringent as to require that the replacement value be a
  713.      sequence of the same type as the sequence of which the subsequence is
  714.      specified.) If the length of the replacement value does not equal the
  715.      length of the subsequence to be replaced, then the shorter length
  716.      determines the number of elements to be stored, as for the function
  717.      replace.
  718.  
  719.    *  A function call form whose first element is the name of any one of the
  720.      following functions, provided that the specified argument to that function
  721.      is in turn a place form; in this case the new place has stored back into
  722.      it the result of applying the specified ``update'' function (which is in
  723.      each of these cases not a true update function):
  724.  
  725.      Function Name   Argument That Is a place    Update Function Used
  726.      ----------------------------------------------------------------
  727.      char-bit        first                       set-char-bit
  728.      ldb             second                      dpb
  729.      mask-field      second                      deposit-field
  730.      ----------------------------------------------------------------
  731.  
  732. [change_begin]
  733.  
  734.      X3J13 voted in March 1989 (CHARACTER-PROPOSAL)   to eliminate char-bit and
  735.      set-char-bit.
  736.  
  737.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  738.      applies only when the function name refers to a global function definition
  739.      and not to a locally defined function or macro.
  740.  
  741. [change_end]
  742.  
  743.    *  A the type declaration form, in which case the declaration is transferred
  744.      to the newvalue form, and the resulting setf form is analyzed. For
  745.      example,
  746.  
  747.      (setf (the integer (cadr x)) (+ y 3))
  748.  
  749.      is processed as if it were
  750.  
  751.      (setf (cadr x) (the integer (+ y 3)))
  752.  
  753.    *  A call to apply where the first argument form is of the form #'name, that
  754.      is, (function name), where name is the name of a function, calls to which
  755.      are recognized as places by setf. Suppose that the use of setf with apply
  756.      looks like this:
  757.  
  758.      (setf (apply #'name x1 x2 ... xn rest) x0)
  759.  
  760.      The setf method for the function name must be such that
  761.  
  762.      (setf (name z1 z2 ... zm) z0)
  763.  
  764.      expands into a store form
  765.  
  766.      (storefn zi   zi   ... zi   zm)
  767.  
  768.      That is, it must expand into a function call such that all arguments but
  769.      the last may be any permutation or subset of the new value z0 and the
  770.      arguments of the access form, but the last argument of the storing call
  771.      must be the same as the last argument of the access call. See
  772.      define-setf-method for more details on accessing and storing forms.
  773.  
  774.      Given this, the setf-of-apply form shown above expands into
  775.  
  776.      (apply #'storefn xi   xi   ... xi   rest)
  777.  
  778.      As an example, suppose that the variable indexes contains a list of
  779.      subscripts for a multidimensional array foo whose rank is not known until
  780.      run time. One may access the indicated element of the array by writing
  781.  
  782.      (apply #'aref foo indexes)
  783.  
  784.      and one may alter the value of the indicated element to that of newvalue
  785.      by writing
  786.  
  787.      (setf (apply #'aref foo indexes) newvalue)
  788.  
  789. [change_begin]
  790.  
  791.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  792.      applies only when the function name apply refers to the global function
  793.      definition and not to a locally defined function or macro named apply.
  794.  
  795. [change_end]
  796.  
  797.    *  A macro call, in which case setf expands the macro call and then analyzes
  798.      the resulting form.
  799.  
  800. [change_begin]
  801.  
  802.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this step uses
  803.      macroexpand-1, not macroexpand. This allows the chance to apply any of the
  804.      rules preceding this one to any of the intermediate expansions.
  805.  
  806. [change_end]
  807.  
  808.    *  Any form for which a defsetf or define-setf-method declaration has been
  809.      made.
  810.  
  811. [change_begin]
  812.  
  813.      X3J13 voted in March 1989 (FUNCTION-NAME)   to clarify that this rule
  814.      applies only when the function name in the form refers to a global
  815.      function definition and not to a locally defined function or macro.
  816.  
  817. X3J13 voted in March 1989 (FUNCTION-NAME)   to add one more rule to the
  818. preceding list, coming after all those listed above:
  819.  
  820.    *  Any other list whose first element is a symbol (call it f). In this case,
  821.      the call to setf expands into a call to the function named by the list
  822.      (setf f) (see section 7.1). The first argument is the new value and the
  823.      remaining arguments are the values of the remaining elements of place.
  824.      This expansion occurs regardless of whether either f or (setf f) is
  825.      defined as a function locally, globally, or not at all. For example,
  826.  
  827.      (setf (f arg1 arg2 ...) newvalue)
  828.  
  829.      expands into a form with the same effect and value as
  830.  
  831.      (let ((#:temp1 arg1)     ;Force correct order of evaluation
  832.            (#:temp2 arg2)
  833.            ...
  834.            (#:temp0 newvalue))
  835.        (funcall (function (setf f))
  836.                 #:temp0
  837.                 #:temp1
  838.                 #:temp2 ...))
  839.  
  840.      By convention, any function named (setf f) should return its first
  841.      argument as its only value, in order to preserve the specification that
  842.      setf returns its newvalue.
  843.  
  844. X3J13 voted in March 1989 (SYMBOL-MACROLET-SEMANTICS)   to add this case as
  845. well:
  846.  
  847.    *  A variable reference that refers to a symbol macro definition made by
  848.      symbol-macrolet, in which case setf expands the reference and then
  849.      analyzes the resulting form.
  850.  
  851. [change_end]
  852.  
  853. setf carefully arranges to preserve the usual left-to-right order in which the
  854. various subforms are evaluated. On the other hand, the exact expansion for any
  855. particular form is not guaranteed and may even be implementation-dependent; all
  856. that is guaranteed is that the expansion of a setf form will be an update form
  857. that works for that particular implementation, and that the left-to-right
  858. evaluation of subforms is preserved.
  859.  
  860. The ultimate result of evaluating a setf form is the value of newvalue.
  861. Therefore (setf (car x) y) does not expand into precisely (rplaca x y), but
  862. into something more like
  863.  
  864. (let ((G1 x) (G2 y)) (rplaca G1 G2) G2)
  865.  
  866. the precise expansion being implementation-dependent.
  867.  
  868. The user can define new setf expansions by using defsetf.
  869.  
  870. [change_begin]
  871. X3J13 voted in June 1989 (SETF-MULTIPLE-STORE-VARIABLES)   to extend the
  872. specification of setf to allow a place whose setf method has more than one
  873. store variable (see define-setf-method). In such a case as many values are
  874. accepted from the newvalue form as there are store variables; extra values are
  875. ignored and missing values default to nil, as is usual in situations involving
  876. multiple values.
  877.  
  878. A proposal was submitted to X3J13 in September 1989 to add a setf method for
  879. values so that one could in fact write, for example,
  880.  
  881. (setf (values quotient remainder)
  882.       (truncate linewidth tabstop))
  883.  
  884. but unless this proposal is accepted users will have to define a setf method
  885. for values themselves (not a difficult task).
  886. [change_end]
  887.  
  888. [Macro]
  889. psetf {place newvalue}*
  890.  
  891. psetf is like setf except that if more than one place-newvalue pair is
  892. specified, then the assignments of new values to places are done in parallel.
  893. More precisely, all subforms that are to be evaluated are evaluated from left
  894. to right; after all evaluations have been performed, all of the assignments are
  895. performed in an unpredictable order. (The unpredictability matters only if more
  896. than one place form refers to the same place.) psetf always returns nil.
  897.  
  898. [change_begin]
  899. X3J13 voted in June 1989 (SETF-MULTIPLE-STORE-VARIABLES)   to extend the
  900. specification of psetf to allow a place whose setf method has more than one
  901. store variable (see define-setf-method). In such a case as many values are
  902. accepted from the newvalue form as there are store variables; extra values are
  903. ignored and missing values default to nil, as is usual in situations involving
  904. multiple values.
  905. [change_end]
  906.  
  907. [Macro]
  908. shiftf {place}+ newvalue
  909.  
  910. Each place form may be any form acceptable as a generalized variable to setf.
  911. In the form (shiftf place1 place2 ... placen newvalue), the values in place1
  912. through placen are accessed and saved, and newvalue is evaluated, for a total
  913. of n+1 values in all. Values 2 through n+1 are then stored into place1 through
  914. placen, and value 1 (the original value of place1) is returned. It is as if all
  915. the places form a shift register; the newvalue is shifted in from the right,
  916. all values shift over to the left one place, and the value shifted out of
  917. place1 is returned. For example:
  918.  
  919. (setq x (list 'a 'b 'c)) => (a b c)
  920.  
  921. (shiftf (cadr x) 'z) => b
  922.    and now x => (a z c)
  923.  
  924. (shiftf (cadr x) (cddr x) 'q) => z
  925.    and now x => (a (c) . q)
  926.  
  927. The effect of (shiftf place1 place2 ... placen newvalue) is equivalent to
  928.  
  929. (let ((var1 place1)
  930.       (var2 place2)
  931.       ...
  932.       (varn placen))
  933.   (setf place1 var2)
  934.   (setf place2 var3)
  935.   ...
  936.   (setf placen newvalue)
  937.   var1)
  938.  
  939. except that the latter would evaluate any subforms of each place twice, whereas
  940. shiftf takes care to evaluate them only once. For example:
  941.  
  942. (setq n 0)
  943. (setq x '(a b c d))
  944. (shiftf (nth (setq n (+ n 1)) x) 'z) => b
  945.    and now x => (a z c d)
  946.  
  947. but
  948.  
  949. (setq n 0)
  950. (setq x '(a b c d))
  951. (prog1 (nth (setq n (+ n 1)) x)
  952.        (setf (nth (setq n (+ n 1)) x) 'z)) => b
  953.    and now x => (a b z d)
  954.  
  955. Moreover, for certain place forms shiftf may be significantly more efficient
  956. than the prog1 version.
  957.  
  958. [change_begin]
  959. X3J13 voted in June 1989 (SETF-MULTIPLE-STORE-VARIABLES)   to extend the
  960. specification of shiftf to allow a place whose setf method has more than one
  961. store variable (see define-setf-method). In such a case as many values are
  962. accepted from the newvalue form as there are store variables; extra values are
  963. ignored and missing values default to nil, as is usual in situations involving
  964. multiple values.
  965. [change_end]
  966.  
  967. -------------------------------------------------------------------------------
  968. Rationale: shiftf and rotatef have been included in Common Lisp as
  969. generalizations of two-argument versions formerly called swapf and exchf. The
  970. two-argument versions have been found to be very useful, but the names were
  971. easily confused. The generalization to many argument forms and the change of
  972. names were both inspired by the work of Suzuki [47], which indicates that use
  973. of these primitives can make certain complex pointer-manipulation programs
  974. clearer and easier to prove correct.
  975. -------------------------------------------------------------------------------
  976.  
  977. [Macro]
  978. rotatef {place}*
  979.  
  980. Each place form may be any form acceptable as a generalized variable to setf.
  981. In the form (rotatef place1 place2 ... placen), the values in place1 through
  982. placen are accessed and saved. Values 2 through n and value 1 are then stored
  983. into place1 through placen. It is as if all the places form an end-around shift
  984. register that is rotated one place to the left, with the value of place1 being
  985. shifted around the end to placen. Note that (rotatef place1 place2) exchanges
  986. the contents of place1 and place2.
  987.  
  988. The effect of (rotatef place1 place2 ... placen) is roughly equivalent to
  989.  
  990. (psetf place1 place2
  991.        place2 place3
  992.        ...
  993.        placen place1)
  994.  
  995. except that the latter would evaluate any subforms of each place twice, whereas
  996. rotatef takes care to evaluate them only once. Moreover, for certain place
  997. forms rotatef may be significantly more efficient.
  998.  
  999. rotatef always returns nil.
  1000.  
  1001. [change_begin]
  1002. X3J13 voted in June 1989 (SETF-MULTIPLE-STORE-VARIABLES)   to extend the
  1003. specification of rotatef to allow a place whose setf method has more than one
  1004. store variable (see define-setf-method). In such a case as many values are
  1005. accepted from the newvalue form as there are store variables; extra values are
  1006. ignored and missing values default to nil, as is usual in situations involving
  1007. multiple values.
  1008. [change_end]
  1009.  
  1010. Other macros that manipulate generalized variables include getf, remf, incf,
  1011. decf, push, pop, assert, ctypecase, and ccase.
  1012.  
  1013. Macros that manipulate generalized variables must guarantee the ``obvious''
  1014. semantics: subforms of generalized-variable references are evaluated exactly as
  1015. many times as they appear in the source program, and they are evaluated in
  1016. exactly the same order as they appear in the source program.
  1017.  
  1018. In generalized-variable references such as shiftf, incf, push, and setf of ldb,
  1019. the generalized variables are both read and written in the same reference.
  1020. Preserving the source program order of evaluation and the number of evaluations
  1021. is particularly important.
  1022.  
  1023. As an example of these semantic rules, in the generalized-variable reference
  1024. (setf reference value) the value form must be evaluated after all the subforms
  1025. of the reference because the value form appears to the right of them.
  1026.  
  1027. The expansion of these macros must consist of code that follows these rules or
  1028. has the same effect as such code. This is accomplished by introducing temporary
  1029. variables bound to the subforms of the reference. As an optimization in the
  1030. implementation, temporary variables may be eliminated whenever it can be proved
  1031. that removing them has no effect on the semantics of the program. For example,
  1032. a constant need never be saved in a temporary variable. A variable, or for that
  1033. matter any form that does not have side effects, need not be saved in a
  1034. temporary variable if it can be proved that its value will not change within
  1035. the scope of the generalized-variable reference.
  1036.  
  1037. Common Lisp provides built-in facilities to take care of these semantic
  1038. complications and optimizations. Since the required semantics can be guaranteed
  1039. by these facilities, the user does not have to worry about writing correct code
  1040. for them, especially in complex cases. Even experts can become confused and
  1041. make mistakes while writing this sort of code.
  1042.  
  1043. [change_begin]
  1044. X3J13 voted in March 1988 (PUSH-EVALUATION-ORDER)   to clarify the preceding
  1045. discussion about the order of evaluation of subforms in calls to setf and
  1046. related macros. The general intent is clear: evaluation proceeds from left to
  1047. right whenever possible. However, the left-to-right rule does not remove the
  1048. obligation on writers of macros and define-setf-method to work to ensure
  1049. left-to-right order of evaluation.
  1050.  
  1051. Let it be emphasized that, in the following discussion, a form is something
  1052. whose syntactic use is such that it will be evaluated. A subform means a form
  1053. that is nested inside another form, not merely any Lisp object nested inside a
  1054. form regardless of syntactic context.
  1055.  
  1056. The evaluation ordering of subforms within a generalized variable reference is
  1057. determined by the order specified by the second value returned by
  1058. get-setf-method. For all predefined generalized variable references (getf,
  1059. ldb), this order of evaluation is exactly left-to-right. When a generalized
  1060. variable reference is derived from a macro expansion, this rule is applied
  1061. after the macro is expanded to find the appropriate generalized variable
  1062. reference.
  1063.  
  1064. This is intended to make it clear that if the user writes a defmacro or
  1065. define-setf-method macro that doesn't preserve left-to-right evaluation order,
  1066. the order specified in the user's code holds. For example, given
  1067.  
  1068. (defmacro wrong-order (x y) `(getf ,y ,x))
  1069.  
  1070. then
  1071.  
  1072. (push value (wrong-order place1 place2))
  1073.  
  1074. will evaluate place2 first and then place1 because that is the order they are
  1075. evaluated in the macro expansion.
  1076.  
  1077. For the macros that manipulate generalized variables (push, pushnew, getf,
  1078. remf, incf, decf, shiftf, rotatef, psetf, setf, pop, and those defined with
  1079. define-modify-macro) the subforms of the macro call are evaluated exactly once
  1080. in left-to-right order, with the subforms of the generalized variable
  1081. references evaluated in the order specified above.
  1082.  
  1083. Each of push, pushnew, getf, remf, incf, decf, shiftf, rotatef, psetf, and pop
  1084. evaluates all subforms before modifying any of the generalized variable
  1085. locations. Moreover, setf itself, in the case when a call on it has more than
  1086. two arguments, performs its operation on each pair in sequence. That is, in
  1087.  
  1088. (setf place1 value1 place2 value2 ...)
  1089.  
  1090. the subforms of place1 and value1 are evaluated, the location specified by
  1091. place1 is modified to contain the value returned by value1, and then the rest
  1092. of the setf form is processed in a like manner.
  1093.  
  1094. For the macros check-type, ctypecase, and ccase, subforms of the generalized
  1095. variable reference are evaluated once per test of a generalized variable, but
  1096. they may be evaluated again if the type check fails (in the case of check-type)
  1097. or if none of the cases holds (in ctypecase or ccase).
  1098.  
  1099. For the macro assert, the order of evaluation of the generalized variable
  1100. references is not specified.
  1101. [change_end]
  1102.  
  1103. Another reason for building in these functions is that the appropriate
  1104. optimizations will differ from implementation to implementation. In some
  1105. implementations most of the optimization is performed by the compiler, while in
  1106. others a simpler compiler is used and most of the optimization is performed in
  1107. the macros. The cost of binding a temporary variable relative to the cost of
  1108. other Lisp operations may differ greatly between one implementation and
  1109. another, and some implementations may find it best never to remove temporary
  1110. variables except in the simplest cases.
  1111.  
  1112. A good example of the issues involved can be seen in the following
  1113. generalized-variable reference:
  1114.  
  1115. (incf (ldb byte-field variable))
  1116.  
  1117. This ought to expand into something like
  1118.  
  1119. (setq variable
  1120.       (dpb (1+ (ldb byte-field variable))
  1121.            byte-field
  1122.            variable))
  1123.  
  1124. In this expansion example we have ignored the further complexity of returning
  1125. the correct value, which is the incremented byte, not the new value of
  1126. variable. Note that the variable byte-field is evaluated twice, and the
  1127. variable variable is referred to three times: once as the location in which to
  1128. store a value, and twice during the computation of that value.
  1129.  
  1130. Now consider this expression:
  1131.  
  1132. (incf (ldb (aref byte-fields (incf i))
  1133.            (aref (determine-words-array) i)))
  1134.  
  1135. It ought to expand into something like this:
  1136.  
  1137. (let ((temp1 (aref byte-fields (incf i)))
  1138.       (temp2 (determine-words-array)))
  1139.   (setf (aref temp2 i)
  1140.         (dpb (1+ (ldb temp1 (aref temp2 i)))
  1141.              temp1
  1142.              (aref temp2 i))))
  1143.  
  1144. Again we have ignored the complexity of returning the correct value. What is
  1145. important here is that the expressions (incf i) and (determine-words-array)
  1146. must not be duplicated because each may have a side effect or be affected by
  1147. side effects.
  1148.  
  1149. [change_begin]
  1150. X3J13 voted in January 1989 (SETF-SUB-METHODS)   to specify more precisely the
  1151. order of evaluation of subforms when setf is used with an access function that
  1152. itself takes a place as an argument, for example, ldb, mask-field, and getf.
  1153. (The vote also discussed the function char-bit, but another vote
  1154. (CHARACTER-PROPOSAL)   removed that function from the language.) The setf
  1155. methods for such accessors produce expansions that effectively require explicit
  1156. calls to get-setf-method.
  1157.  
  1158. The code produced as the macro expansion of a setf form that itself admits a
  1159. generalized variable as an argument must essentially do the following major
  1160. steps:
  1161.  
  1162.    *  It evaluates the value-producing subforms, in left-to-right order, and
  1163.      binds the temporary variables to them; this is called binding the
  1164.      temporaries.
  1165.  
  1166.    *  It reads the value from the generalized variable, using the supplied
  1167.      accessing form, to get the old value; this is called doing the access.
  1168.      Note that this is done after all the evaluations of the preceding step,
  1169.      including any side effects they may have.
  1170.  
  1171.    *  It binds the store variable to a new value, and then installs this new
  1172.      value into the generalized variable using the supplied storing form; this
  1173.      is called doing the store.
  1174.  
  1175. Doing the access for a generalized variable reference is not part of the series
  1176. of evaluations that must be done in left-to-right order.
  1177.  
  1178. The place-specifier forms ldb, mask-field, and getf admit (other) place
  1179. specifiers as arguments. During the setf expansion of these forms, it is
  1180. necessary to call get-setf-method to determine how the inner, nested
  1181. generalized variable must be treated.
  1182.  
  1183. In a form such as
  1184.  
  1185. (setf (ldb byte-spec place-form) newvalue-form)
  1186.  
  1187. the place referred to by the place-form must always be both accessed and
  1188. updated; note that the update is to the generalized variable specified by
  1189. place-form, not to any object of type integer.
  1190.  
  1191. Thus this call to setf should generate code to do the following:
  1192.  
  1193.    *  Evaluate byte-spec and bind into a temporary
  1194.    *  Bind the temporaries for place-form
  1195.    *  Evaluate newvalue-form and bind into the store variable
  1196.    *  Do the access to place-form
  1197.    *  Do the store into place-form with the given bit-field of the accessed
  1198.      integer replaced with the value in the store variable
  1199.  
  1200. If the evaluation of newvalue-form alters what is found in the given place-such
  1201. as setting a different bit-field of the integer-then the change of the
  1202. bit-field denoted by byte-spec will be to that altered integer, because the
  1203. access step must be done after the newvalue-form evaluation. Nevertheless, the
  1204. evaluations required for binding the temporaries are done before the evaluation
  1205. of the newvalue-form, thereby preserving the required left-to-right evaluation
  1206. order.
  1207.  
  1208. The treatment of mask-field is similar to that of ldb.
  1209.  
  1210. In a form such as:
  1211.  
  1212. (setf (getf place-form ind-form) newvalue-form)
  1213.  
  1214. the place referred to by the place-form must always be both accessed and
  1215. updated; note that the update is to the generalized variable specified by
  1216. place-form, not necessarily to the particular list which is the property list
  1217. in question.
  1218.  
  1219. Thus this call to setf should generate code to do the following:
  1220.  
  1221.    *  Bind the temporaries for place-form
  1222.    *  Evaluate ind-form and bind into a temporary
  1223.    *  Evaluate the newvalue-form and bind into the store variable
  1224.    *  Do the access to place-form
  1225.    *  Do the store into place-form with a possibly new property list obtained
  1226.      by combining the results of the evaluations and the access
  1227.  
  1228. If the evaluation of newvalue-form alters what is found in the given place-such
  1229. as setting a different named property in the list-then the change of the
  1230. property denoted by ind-form will be to that altered list, because the access
  1231. step is done after the newvalue-form evaluation. Nevertheless, the evaluations
  1232. required for binding the temporaries are done before the evaluation of the
  1233. newvalue-form, thereby preserving the required left-to-right evaluation order.
  1234.  
  1235. Note that the phrase ``possibly new property list'' treats the implementation
  1236. of property lists as a ``black box''; it can mean that the former property list
  1237. is somehow destructively re-used, or it can mean partial or full copying of it.
  1238. A side effect may or may not occur; therefore setf must proceed as if the
  1239. resultant property list were a different copy needing to be stored back into
  1240. the generalized variable.
  1241. [change_end]
  1242.  
  1243. The Common Lisp facilities provided to deal with these semantic issues include:
  1244.  
  1245.    *  Built-in macros such as setf and push that follow the semantic rules.
  1246.  
  1247.    *  The define-modify-macro macro, which allows new generalized-variable
  1248.      manipulating macros (of a certain restricted kind) to be defined easily.
  1249.      It takes care of the semantic rules automatically.
  1250.  
  1251.    *  The defsetf macro, which allows new types of generalized-variable
  1252.      references to be defined easily. It takes care of the semantic rules
  1253.      automatically.
  1254.  
  1255.    *  The define-setf-method macro and the get-setf-method function, which
  1256.      provide access to the internal mechanisms when it is necessary to define a
  1257.      complicated new type of generalized-variable reference or
  1258.      generalized-variable-manipulating macro.
  1259.  
  1260. [change_begin]
  1261. Also important are the changes that allow lexical environments to be used in
  1262. appropriate ways in setf methods.
  1263. [change_end]
  1264.  
  1265. [Macro]
  1266. define-modify-macro name lambda-list function
  1267. [doc-string]
  1268.  
  1269. This macro defines a read-modify-write macro named name. An example of such a
  1270. macro is incf. The first subform of the macro will be a generalized-variable
  1271. reference. The function is literally the function to apply to the old contents
  1272. of the generalized-variable to get the new contents; it is not evaluated.
  1273. lambda-list describes the remaining arguments for the function; these arguments
  1274. come from the remaining subforms of the macro after the generalized-variable
  1275. reference. lambda-list may contain &optional and &rest markers. (The &key
  1276. marker is not permitted here; &rest suffices for the purposes of
  1277. define-modify-macro.) doc-string is documentation for the macro name being
  1278. defined.
  1279.  
  1280. The expansion of a define-modify-macro is equivalent to the following, except
  1281. that it generates code that follows the semantic rules outlined above.
  1282.  
  1283. (defmacro name (reference . lambda-list)
  1284.   doc-string
  1285.   `(setf ,reference
  1286.          (function ,reference ,arg1 ,arg2 ...)))
  1287.  
  1288. where arg1, arg2, ..., are the parameters appearing in lambda-list; appropriate
  1289. provision is made for a &rest parameter.
  1290.  
  1291. As an example, incf could have been defined by:
  1292.  
  1293. (define-modify-macro incf (&optional (delta 1)) +)
  1294.  
  1295. An example of a possibly useful macro not predefined in Common Lisp is
  1296.  
  1297. (define-modify-macro unionf (other-set &rest keywords) union)
  1298.  
  1299. [change_begin]
  1300. X3J13 voted in March 1988 (GET-SETF-METHOD-ENVIRONMENT)   to specify that
  1301. define-modify-macro creates macros that take &environment arguments and perform
  1302. the equivalent of correctly passing such lexical environments to
  1303. get-setf-method in order to correctly maintain lexical references.
  1304. [change_end]
  1305.  
  1306. [Macro]
  1307.  
  1308. defsetf access-fn {update-fn [doc-string] |
  1309.  
  1310.                    lambda-list (store-variable)
  1311.  
  1312.                    [[{declaration}* | doc-string]] {form}*}
  1313.  
  1314. This defines how to setf a generalized-variable reference of the form
  1315. (access-fn ...). The value of a generalized-variable reference can always be
  1316. obtained simply by evaluating it, so access-fn should be the name of a function
  1317. or a macro.
  1318.  
  1319. The user of defsetf provides a description of how to store into the
  1320. generalized-variable reference and return the value that was stored (because
  1321. setf is defined to return this value). The implementation of defsetf takes care
  1322. of ensuring that subforms of the reference are evaluated exactly once and in
  1323. the proper left-to-right order. In order to do this, defsetf requires that
  1324. access-fn be a function or a macro that evaluates its arguments, behaving like
  1325. a function. Furthermore, a setf of a call on access-fn will also evaluate all
  1326. of access-fn's arguments; it cannot treat any of them specially. This means
  1327. that defsetf cannot be used to describe how to store into a generalized
  1328. variable that is a byte, such as (ldb field reference). To handle situations
  1329. that do not fit the restrictions imposed by defsetf, use define-setf-method,
  1330. which gives the user additional control at the cost of increased complexity.
  1331.  
  1332. A defsetf declaration may take one of two forms. The simple form is
  1333.  
  1334. (defsetf access-fn update-fn doc-string)
  1335.  
  1336. The update-fn must name a function (or macro) that takes one more argument than
  1337. access-fn takes. When setf is given a place that is a call on access-fn, it
  1338. expands into a call on update-fn that is given all the arguments to access-fn
  1339. and also, as its last argument, the new value (which must be returned by
  1340. update-fn as its value). For example, the effect of
  1341.  
  1342. (defsetf symbol-value set)
  1343.  
  1344. is built into the Common Lisp system. This causes the expansion
  1345.  
  1346. (setf (symbol-value foo) fu) -> (set foo fu)
  1347.  
  1348. for example. Note that
  1349.  
  1350. (defsetf car rplaca)
  1351.  
  1352. would be incorrect because rplaca does not return its last argument.
  1353.  
  1354. The complex form of defsetf looks like
  1355.  
  1356. (defsetf access-fn lambda-list (store-variable) . body)
  1357.  
  1358. and resembles defmacro. The body must compute the expansion of a setf of a call
  1359. on access-fn.
  1360.  
  1361. The lambda-list describes the arguments of access-fn. &optional, &rest, and
  1362. &key markers are permitted in lambda-list. Optional arguments may have defaults
  1363. and ``supplied-p'' flags. The store-variable describes the value to be stored
  1364. into the generalized-variable reference.
  1365.  
  1366. -------------------------------------------------------------------------------
  1367. Rationale: The store-variable is enclosed in parentheses to provide for an
  1368. extension to multiple store variables that would receive multiple values from
  1369. the second subform of setf. The rules given below for coding setf methods
  1370. discuss the proper handling of multiple store variables to allow for the
  1371. possibility that this extension may be incorporated into Common Lisp in the
  1372. future.
  1373. -------------------------------------------------------------------------------
  1374.  
  1375. The body forms can be written as if the variables in the lambda-list were bound
  1376. to subforms of the call on access-fn and the store-variable were bound to the
  1377. second subform of setf. However, this is not actually the case. During the
  1378. evaluation of the body forms, these variables are bound to names of temporary
  1379. variables, generated as if by gensym or gentemp, that will be bound by the
  1380. expansion of setf to the values of those subforms. This binding permits the
  1381. body forms to be written without regard for order-of-evaluation issues. defsetf
  1382. arranges for the temporary variables to be optimized out of the final result in
  1383. cases where that is possible. In other words, an attempt is made by defsetf to
  1384. generate the best code possible in a particular implementation.
  1385.  
  1386. Note that the code generated by the body forms must include provision for
  1387. returning the correct value (the value of store-variable). This is handled by
  1388. the body forms rather than by defsetf because in many cases this value can be
  1389. returned at no extra cost, by calling a function that simultaneously stores
  1390. into the generalized variable and returns the correct value.
  1391.  
  1392. An example of the use of the complex form of defsetf:
  1393.  
  1394. (defsetf subseq (sequence start &optional end) (new-sequence)
  1395.   `(progn (replace ,sequence ,new-sequence
  1396.                    :start1 ,start :end1 ,end)
  1397.           ,new-sequence))
  1398.  
  1399. [change_begin]
  1400. X3J13 voted in March 1988 (FLET-IMPLICIT-BLOCK)   to specify that the body of
  1401. the expander function defined by the complex form of defsetf is implicitly
  1402. enclosed in a block construct whose name is the same as the name of the
  1403. access-fn. Therefore return-from may be used to exit from the function.
  1404.  
  1405. X3J13 voted in March 1989 (DEFINING-MACROS-NON-TOP-LEVEL)   to clarify that,
  1406. while defining forms normally appear at top level, it is meaningful to place
  1407. them in non-top-level contexts; the complex form of defsetf must define the
  1408. expander function within the enclosing lexical environment, not within the
  1409. global environment.
  1410. [change_end]
  1411.  
  1412. The underlying theory by which setf and related macros arrange to conform to
  1413. the semantic rules given above is that from any generalized-variable reference
  1414. one may derive its ``setf method,'' which describes how to store into that
  1415. reference and which subforms of it are evaluated.
  1416.  
  1417. -------------------------------------------------------------------------------
  1418. Compatibility note: To avoid confusion, it should be noted that the use of the
  1419. word ``method'' here in connection with setf has nothing to do with its use in
  1420. Lisp Machine Lisp in connection with message-passing and the Lisp Machine Lisp
  1421. ``flavor system.''
  1422. [change_begin]
  1423. And of course it also has nothing to do with the methods in the Common Lisp
  1424. Object System (CLOS)   .
  1425. [change_end]
  1426. -------------------------------------------------------------------------------
  1427.  
  1428. Given knowledge of the subforms of the reference, it is possible to avoid
  1429. evaluating them multiple times or in the wrong order. A setf method for a given
  1430. access form can be expressed as five values:
  1431.  
  1432.    *  A list of temporary variables
  1433.  
  1434.    *  A list of value forms (subforms of the given form) to whose values the
  1435.      temporary variables are to be bound
  1436.  
  1437.    *  A second list of temporary variables, called store variables
  1438.  
  1439.    *  A storing form
  1440.  
  1441.    *  An accessing form
  1442.  
  1443. The temporary variables will be bound to the values of the value forms as if by
  1444. let*; that is, the value forms will be evaluated in the order given and may
  1445. refer to the values of earlier value forms by using the corresponding
  1446. variables.
  1447.  
  1448. The store variables are to be bound to the values of the newvalue form, that
  1449. is, the values to be stored into the generalized variable. In almost all cases
  1450. only a single value is to be stored, and there is only one store variable.
  1451.  
  1452. The storing form and the accessing form may contain references to the temporary
  1453. variables (and also, in the case of the storing form, to the store variables).
  1454. The accessing form returns the value of the generalized variable. The storing
  1455. form modifies the value of the generalized variable and guarantees to return
  1456. the values of the store variables as its values; these are the correct values
  1457. for setf to return. (Again, in most cases there is a single store variable and
  1458. thus a single value to be returned.) The value returned by the accessing form
  1459. is, of course, affected by execution of the storing form, but either of these
  1460. forms may be evaluated any number of times and therefore should be free of side
  1461. effects (other than the storing action of the storing form).
  1462.  
  1463. The temporary variables and the store variables are generated names, as if by
  1464. gensym or gentemp, so that there is never any problem of name clashes among
  1465. them, or between them and other variables in the program. This is necessary to
  1466. make the special forms that do more than one setf in parallel work properly;
  1467. these are psetf, shiftf, and rotatef. Computation of the setf method must
  1468. always create new variable names; it may not return the same ones every time.
  1469.  
  1470. Some examples of setf methods for particular forms:
  1471.  
  1472.    *  For a variable x:
  1473.  
  1474.      ()
  1475.      ()
  1476.      (g0001)
  1477.      (setq x g0001)
  1478.      x
  1479.  
  1480.    *  For (car exp):
  1481.  
  1482.      (g0002)
  1483.      (exp)
  1484.      (g0003)
  1485.      (progn (rplaca g0002 g0003) g0003)
  1486.      (car g0002)
  1487.  
  1488.    *  For (subseq seq s e):
  1489.  
  1490.      (g0004 g0005 g0006)
  1491.      (seq s e)
  1492.      (g0007)
  1493.      (progn (replace g0004 g0007 :start1 g0005 :end1 g0006)
  1494.             g0007)
  1495.      (subseq g0004 g0005 g0006)
  1496.  
  1497. [Macro]
  1498.  
  1499. define-setf-method access-fn lambda-list
  1500.                    [[ {declaration}* | doc-string ]]  {form}*
  1501.  
  1502. This defines how to setf a generalized-variable reference that is of the form
  1503. (access-fn...). The value of a generalized-variable reference can always be
  1504. obtained simply by evaluating it, so access-fn should be the name of a function
  1505. or a macro.
  1506.  
  1507. The lambda-list describes the subforms of the generalized-variable reference,
  1508. as with defmacro. The result of evaluating the forms in the body must be five
  1509. values representing the setf method, as described above. Note that
  1510. define-setf-method differs from the complex form of defsetf in that while the
  1511. body is being executed the variables in lambda-list are bound to parts of the
  1512. generalized-variable reference, not to temporary variables that will be bound
  1513. to the values of such parts. In addition, define-setf-method does not have
  1514. defsetf's restriction that access-fn must be a function or a function-like
  1515. macro; an arbitrary defmacro destructuring pattern is permitted in lambda-list.
  1516.  
  1517. By definition there are no good small examples of define-setf-method because
  1518. the easy cases can all be handled by defsetf. A typical use is to define the
  1519. setf method for ldb:
  1520.  
  1521. ;;; SETF method for the form (LDB bytespec int).
  1522. ;;; Recall that the int form must itself be suitable for SETF.
  1523. (define-setf-method ldb (bytespec int)
  1524.   (multiple-value-bind (temps vals stores
  1525.                         store-form access-form)
  1526.       (get-setf-method int)         ;Get SETF method for int
  1527.     (let ((btemp (gensym))          ;Temp var for byte specifier
  1528.           (store (gensym))          ;Temp var for byte to store
  1529.           (stemp (first stores)))   ;Temp var for int to store
  1530.       ;; Return the SETF method for LDB as five values.
  1531.       (values (cons btemp temps)    ;Temporary variables
  1532.               (cons bytespec vals)  ;Value forms
  1533.               (list store)          ;Store variables
  1534.               `(let ((,stemp (dpb ,store ,btemp ,access-form)))
  1535.                  ,store-form
  1536.                  ,store)                     ;Storing form
  1537.               `(ldb ,btemp ,access-form)     ;Accessing form
  1538.               ))))
  1539.  
  1540. [change_begin]
  1541. X3J13 voted in March 1988 (GET-SETF-METHOD-ENVIRONMENT)   to specify that the
  1542. &environment lambda-list keyword may appear in the lambda-list in the same
  1543. manner as for defmacro in order to obtain the lexical environment of the call
  1544. to the setf macro. The preceding example should be modified to take advantage
  1545. of this new feature. The setf method must accept an &environment parameter,
  1546. which will receive the lexical environment of the call to setf; this
  1547. environment must then be given to get-setf-method in order that it may
  1548. correctly use any locally bound setf method that might be applicable to the
  1549. place form that appears as the second argument to ldb in the call to setf.
  1550.  
  1551. ;;; SETF method for the form (LDB bytespec int).
  1552. ;;; Recall that the int form must itself be suitable for SETF.
  1553. ;;; Note the use of an &environment parameter to receive the
  1554. ;;; lexical environment of the call for use with GET-SETF-METHOD.
  1555. (define-setf-method ldb (bytespec int &environment env)
  1556.   (multiple-value-bind (temps vals stores
  1557.                         store-form access-form)
  1558.       (get-setf-method int env)     ;Get SETF method for int
  1559.     (let ((btemp (gensym))          ;Temp var for byte specifier
  1560.           (store (gensym))          ;Temp var for byte to store
  1561.           (stemp (first stores)))   ;Temp var for int to store
  1562.       ;; Return the SETF method for LDB as five values.
  1563.       (values (cons btemp temps)    ;Temporary variables
  1564.               (cons bytespec vals)  ;Value forms
  1565.               (list store)          ;Store variables
  1566.               `(let ((,stemp (dpb ,store ,btemp ,access-form)))
  1567.                  ,store-form
  1568.                  ,store)                     ;Storing form
  1569.               `(ldb ,btemp ,access-form)     ;Accessing form
  1570.               ))))
  1571.  
  1572. X3J13 voted in March 1988 (FLET-IMPLICIT-BLOCK)   to specify that the body of
  1573. the expander function defined by define-setf-method is implicitly enclosed in a
  1574. block construct whose name is the same as the name of the access-fn. Therefore
  1575. return-from may be used to exit from the function.
  1576.  
  1577. X3J13 voted in March 1989 (DEFINING-MACROS-NON-TOP-LEVEL)   to clarify that,
  1578. while defining forms normally appear at top level, it is meaningful to place
  1579. them in non-top-level contexts; define-setf-method must define the expander
  1580. function within the enclosing lexical environment, not within the global
  1581. environment.
  1582. [change_end]
  1583.  
  1584. [old_change_begin]
  1585.  
  1586. [Function]
  1587. get-setf-method form
  1588.  
  1589. get-setf-method returns five values constituting the setf method for form. The
  1590. form must be a generalized-variable reference. get-setf-method takes care of
  1591. error-checking and macro expansion and guarantees to return exactly one store
  1592. variable.
  1593.  
  1594. As an example, an extremely simplified version of setf, allowing no more and no
  1595. fewer than two subforms, containing no optimization to remove unnecessary
  1596. variables, and not allowing storing of multiple values, could be defined by:
  1597.  
  1598. (defmacro setf (reference value)
  1599.   (multiple-value-bind (vars vals stores store-form access-form)
  1600.       (get-setf-method reference)
  1601.     (declare (ignore access-form))
  1602.     `(let* ,(mapcar #'list
  1603.                     (append vars stores)
  1604.                     (append vals (list value)))
  1605.        ,store-form)))
  1606.  
  1607. [old_change_end]
  1608.  
  1609. [change_begin]
  1610. X3J13 voted in March 1988 (GET-SETF-METHOD-ENVIRONMENT)   to add an optional
  1611. environment argument to get-setf-method. The revised definition and example are
  1612. as follows.
  1613.  
  1614. [Function]
  1615. get-setf-method form &optional env
  1616.  
  1617. get-setf-method returns five values constituting the setf method for form. The
  1618. form must be a generalized-variable reference. The env must be an environment
  1619. of the sort obtained through the &environment lambda-list keyword; if env is
  1620. nil or omitted, the null lexical environment is assumed. get-setf-method takes
  1621. care of error checking and macro expansion and guarantees to return exactly one
  1622. store variable.
  1623.  
  1624. As an example, an extremely simplified version of setf, allowing no more and no
  1625. fewer than two subforms, containing no optimization to remove unnecessary
  1626. variables, and not allowing storing of multiple values, could be defined by:
  1627.  
  1628. (defmacro setf (reference value &environment env)
  1629.   (multiple-value-bind (vars vals stores store-form access-form)
  1630.       (get-setf-method reference env)     ;Note use of environment
  1631.     (declare (ignore access-form))
  1632.     `(let* ,(mapcar #'list
  1633.                     (append vars stores)
  1634.                     (append vals (list value)))
  1635.        ,store-form)))
  1636.  
  1637. [change_end]
  1638.  
  1639. [old_change_begin]
  1640.  
  1641. [Function]
  1642. get-setf-method-multiple-value form
  1643.  
  1644. get-setf-method-multiple-value returns five values constituting the setf method
  1645. for form. The form must be a generalized-variable reference. This is the same
  1646. as get-setf-method except that it does not check the number of store variables;
  1647. use this in cases that allow storing multiple values into a generalized
  1648. variable. There are no such cases in standard Common Lisp, but this function is
  1649. provided to allow for possible extensions.
  1650. [old_change_end]
  1651.  
  1652. [change_begin]
  1653. X3J13 voted in March 1988 (GET-SETF-METHOD-ENVIRONMENT)   to add an optional
  1654. environment argument to get-setf-method. The revised definition is as follows.
  1655.  
  1656. [Function]
  1657. get-setf-method-multiple-value form &optional env
  1658.  
  1659. get-setf-method-multiple-value returns five values constituting the setf method
  1660. for form. The form must be a generalized-variable reference. The env must be an
  1661. environment of the sort obtained through the &environment lambda-list keyword;
  1662. if env is nil or omitted, the null lexical environment is assumed.
  1663.  
  1664. This is the same as get-setf-method except that it does not check the number of
  1665. store variables; use this in cases that allow storing multiple values into a
  1666. generalized variable. There are no such cases in standard Common Lisp, but this
  1667. function is provided to allow for possible extensions.
  1668.  
  1669. X3J13 voted in March 1988 (GET-SETF-METHOD-ENVIRONMENT)   to clarify that a
  1670. setf method for a functional name is applicable only when the global binding of
  1671. that name is lexically visible. If such a name has a local binding introduced
  1672. by flet, labels, or macrolet, then global definitions of setf methods for that
  1673. name do not apply and are not visible. All of the standard Common Lisp macros
  1674. that modify a setf place (for example, incf, decf, pop, and rotatef) obey this
  1675. convention.
  1676. [change_end]
  1677.  
  1678. -------------------------------------------------------------------------------
  1679.  
  1680. 7.3. Function Invocation
  1681.  
  1682. The most primitive form for function invocation in Lisp of course has no name;
  1683. any list that has no other interpretation as a macro call or special form is
  1684. taken to be a function call. Other constructs are provided for less common but
  1685. nevertheless frequently useful situations.
  1686.  
  1687. [Function]
  1688. apply function arg &rest more-args
  1689.  
  1690. This applies function to a list of arguments.
  1691.  
  1692. [old_change_begin]
  1693. The function may be a compiled-code object, or a lambda-expression, or a
  1694. symbol; in the latter case the global functional value of that symbol is used
  1695. (but it is illegal for the symbol to be the name of a macro or special form).
  1696. [old_change_end]
  1697.  
  1698. [change_begin]
  1699. X3J13 voted in June 1988 (FUNCTION-TYPE)   to allow the function to be only of
  1700. type symbol or function; a lambda-expression is no longer acceptable as a
  1701. functional argument. One must use the function special form or the abbreviation
  1702. #' before a lambda-expression that appears as an explicit argument form.
  1703. [change_end]
  1704.  
  1705. The arguments for the function consist of the last argument to apply appended
  1706. to the end of a list of all the other arguments to apply but the function
  1707. itself; it is as if all the arguments to apply except the function were given
  1708. to list* to create the argument list. For example:
  1709.  
  1710. (setq f '+) (apply f '(1 2)) => 3
  1711. (setq f #'-) (apply f '(1 2)) => -1
  1712. (apply #'max 3 5 '(2 7 3)) => 7
  1713. (apply 'cons '((+ 2 3) 4)) =>
  1714.         ((+ 2 3) . 4) not (5 . 4)
  1715. (apply #'+ '()) => 0
  1716.  
  1717. Note that if the function takes keyword arguments, the keywords as well as the
  1718. corresponding values must appear in the argument list:
  1719.  
  1720. (apply #'(lambda (&key a b) (list a b)) '(:b 3)) => (nil 3)
  1721.  
  1722. This can be very useful in conjunction with the &allow-other-keys feature:
  1723.  
  1724. (defun foo (size &rest keys &key double &allow-other-keys)
  1725.   (let ((v (apply #'make-array size :allow-other-keys t keys)))
  1726.     (if double (concatenate (type-of v) v v) v)))
  1727.  
  1728. (foo 4 :initial-contents '(a b c d) :double t)
  1729.    => #(a b c d a b c d)
  1730.  
  1731. [Function]
  1732. funcall fn &rest arguments
  1733.  
  1734. (funcall fn a1 a2 ... an) applies the function fn to the arguments a1, a2, ...,
  1735. an. The fn may not be a special form or a macro; this would not be meaningful.
  1736.  
  1737. [change_begin]
  1738. X3J13 voted in June 1988 (FUNCTION-TYPE)   to allow the fn to be only of type
  1739. symbol or function; a lambda-expression is no longer acceptable as a functional
  1740. argument. One must use the function special form or the abbreviation #' before
  1741. a lambda-expression that appears as an explicit argument form.
  1742. [change_end]
  1743.  
  1744. For example:
  1745.  
  1746. (cons 1 2) => (1 . 2)
  1747. (setq cons (symbol-function '+))
  1748. (funcall cons 1 2) => 3
  1749.  
  1750. The difference between funcall and an ordinary function call is that the
  1751. function is obtained by ordinary Lisp evaluation rather than by the special
  1752. interpretation of the function position that normally occurs.
  1753.  
  1754. -------------------------------------------------------------------------------
  1755. Compatibility note: The Common Lisp function funcall corresponds roughly to the
  1756. Interlisp primitive apply*.
  1757. -------------------------------------------------------------------------------
  1758.  
  1759. [Constant]
  1760. call-arguments-limit
  1761.  
  1762. The value of call-arguments-limit is a positive integer that is the upper
  1763. exclusive bound on the number of arguments that may be passed to a function.
  1764. This bound depends on the implementation but will not be smaller than 50.
  1765. (Implementors are encouraged to make this limit as large as practicable without
  1766. sacrificing performance.) The value of call-arguments-limit must be at least as
  1767. great as that of lambda-parameters-limit. See also multiple-values-limit.
  1768.  
  1769. -------------------------------------------------------------------------------
  1770.  
  1771. 7.4. Simple Sequencing
  1772.  
  1773. Each of the constructs in this section simply evaluates all the argument forms
  1774. in order. They differ only in what results are returned.
  1775.  
  1776. [Special Form]
  1777. progn {form}*
  1778.  
  1779. The progn construct takes a number of forms and evaluates them sequentially, in
  1780. order, from left to right. The values of all the forms but the last are
  1781. discarded; whatever the last form returns is returned by the progn form. One
  1782. says that all the forms but the last are evaluated for effect, because their
  1783. execution is useful only for the side effects caused, but the last form is
  1784. executed for value.
  1785.  
  1786. progn is the primitive control structure construct for ``compound statements,''
  1787. such as begin-end blocks in Algol-like languages. Many Lisp constructs are
  1788. ``implicit progn'' forms: as part of their syntax each allows many forms to be
  1789. written that are to be evaluated sequentially, discarding the results of all
  1790. forms but the last and returning the results of the last form.
  1791.  
  1792. If the last form of the progn returns multiple values, then those multiple
  1793. values are returned by the progn form. If there are no forms for the progn,
  1794. then the result is nil. These rules generally hold for implicit progn forms as
  1795. well.
  1796.  
  1797. [Macro]
  1798. prog1 first {form}*
  1799.  
  1800. prog1 is similar to progn, but it returns the value of its first form. All the
  1801. argument forms are executed sequentially; the value of the first form is saved
  1802. while all the others are executed and is then returned.
  1803.  
  1804. prog1 is most commonly used to evaluate an expression with side effects and to
  1805. return a value that must be computed before the side effects happen. For
  1806. example:
  1807.  
  1808. (prog1 (car x) (rplaca x 'foo))
  1809.  
  1810. alters the car of x to be foo and returns the old car of x.
  1811.  
  1812. prog1 always returns a single value, even if the first form tries to return
  1813. multiple values. As a consequence, (prog1 x) and (progn x) may behave
  1814. differently if x can produce multiple values. See multiple-value-prog1. A point
  1815. of style: although prog1 can be used to force exactly a single value to be
  1816. returned, it is conventional to use the function values for this purpose.
  1817.  
  1818. [Macro]
  1819. prog2 first second {form}*
  1820.  
  1821. prog2 is similar to prog1, but it returns the value of its second form. All the
  1822. argument forms are executed sequentially; the value of the second form is saved
  1823. while all the other forms are executed and is then returned. prog2 is provided
  1824. mostly for historical compatibility.
  1825.  
  1826. (prog2 a b c ... z) == (progn a (prog1 b c ... z))
  1827.  
  1828. Occasionally it is desirable to perform one side effect, then a value-producing
  1829. operation, then another side effect. In such a peculiar case, prog2 is fairly
  1830. perspicuous. For example:
  1831.  
  1832. (prog2 (open-a-file) (process-the-file) (close-the-file))
  1833.                      ;value is that of process-the-file
  1834.  
  1835. prog2, like prog1, always returns a single value, even if the second form tries
  1836. to return multiple values. As a consequence of this, (prog2 x y) and (progn x
  1837. y) may behave differently if y can produce multiple values.
  1838.  
  1839. -------------------------------------------------------------------------------
  1840.  
  1841. 7.5. Establishing New Variable Bindings
  1842.  
  1843. During the invocation of a function represented by a lambda-expression (or a
  1844. closure of a lambda-expression, as produced by function), new bindings are
  1845. established for the variables that are the parameters of the lambda-expression.
  1846. These bindings initially have values determined by the parameter-binding
  1847. protocol discussed in section 5.2.2.
  1848.  
  1849. The following constructs may also be used to establish bindings of variables,
  1850. both ordinary and functional.
  1851.  
  1852. [Special Form]
  1853. let ({var | (var value)}*) {declaration}* {form}*
  1854.  
  1855. A let form can be used to execute a series of forms with specified variables
  1856. bound to specified values.
  1857.  
  1858. More precisely, the form
  1859.  
  1860. (let ((var1 value1)
  1861.       (var2 value2)
  1862.       ...
  1863.       (varm valuem))
  1864.   declaration1
  1865.   declaration2
  1866.   ...
  1867.   declarationp
  1868.   body1
  1869.   body2
  1870.   ...
  1871.   bodyn)
  1872.  
  1873. first evaluates the expressions value1, value2, and so on, in that order,
  1874. saving the resulting values. Then all of the variables varj are bound to the
  1875. corresponding values in parallel; each binding will be a lexical binding unless
  1876. there is a special declaration to the contrary. The expressions bodyk are then
  1877. evaluated in order; the values of all but the last are discarded (that is, the
  1878. body of a let form is an implicit progn). The let form returns what evaluating
  1879. bodyn produces (if the body is empty, which is fairly useless, let returns nil
  1880. as its value). The bindings of the variables have lexical scope and indefinite
  1881. extent.
  1882.  
  1883. Instead of a list (varj valuej), one may write simply varj. In this case varj
  1884. is initialized to nil. As a matter of style, it is recommended that varj be
  1885. written only when that variable will be stored into (such as by setq) before
  1886. its first use. If it is important that the initial value be nil rather than
  1887. some undefined value, then it is clearer to write out (varj nil) if the initial
  1888. value is intended to mean ``false,'' or (varj '()) if the initial value is
  1889. intended to be an empty list. Note that the code
  1890.  
  1891. (let (x)
  1892.   (declare (integer x))
  1893.   (setq x (gcd y z))
  1894.   ...)
  1895.  
  1896. is incorrect; although x is indeed set before it is used, and is set to a value
  1897. of the declared type integer, nevertheless x momentarily takes on the value nil
  1898. in violation of the type declaration.
  1899.  
  1900. Declarations may appear at the beginning of the body of a let. See declare.
  1901.  
  1902. [change_begin]
  1903. See also destructuring-bind.
  1904.  
  1905. X3J13 voted in January 1989 (VARIABLE-LIST-ASYMMETRY)   to regularize the
  1906. binding formats for do, do*, let, let*, prog, prog*, and compiler-let. The new
  1907. syntactic definition for let makes the value optional:
  1908.  
  1909. [Special Form]
  1910. let ({var | (var [value])}*) {declaration}* {form}*
  1911.  
  1912. This changes let to allow a list (var) to appear, meaning the same as simply
  1913. var.
  1914. [change_end]
  1915.  
  1916. [Special Form]
  1917. let* ({var | (var value)}*) {declaration}* {form}*
  1918.  
  1919. let* is similar to let, but the bindings of variables are performed
  1920. sequentially rather than in parallel. This allows the expression for the value
  1921. of a variable to refer to variables previously bound in the let* form.
  1922.  
  1923. More precisely, the form
  1924.  
  1925. (let* ((var1 value1)
  1926.        (var2 value2)
  1927.        ...
  1928.        (varm valuem))
  1929.   declaration1
  1930.   declaration2
  1931.   ...
  1932.   declarationp
  1933.   body1
  1934.   body2
  1935.   ...
  1936.   bodyn)
  1937.  
  1938. first evaluates the expression value1, then binds the variable var1 to that
  1939. value; then it evaluates value2 and binds var2; and so on. The expressions
  1940. bodyj are then evaluated in order; the values of all but the last are discarded
  1941. (that is, the body of a let* form is an implicit progn). The let* form returns
  1942. the results of evaluating bodyn (if the body is empty, which is fairly useless,
  1943. let* returns nil as its value). The bindings of the variables have lexical
  1944. scope and indefinite extent.
  1945.  
  1946. Instead of a list (varj valuej), one may write simply varj. In this case varj
  1947. is initialized to nil. As a matter of style, it is recommended that varj be
  1948. written only when that variable will be stored into (such as by setq) before
  1949. its first use. If it is important that the initial value be nil rather than
  1950. some undefined value, then it is clearer to write out (varj nil) if the initial
  1951. value is intended to mean ``false,'' or (varj '()) if the initial value is
  1952. intended to be an empty list.
  1953.  
  1954. Declarations may appear at the beginning of the body of a let*. See declare.
  1955.  
  1956. [change_begin]
  1957. X3J13 voted in January 1989 (VARIABLE-LIST-ASYMMETRY)   to regularize the
  1958. binding formats for do, do*, let, let*, prog, prog*, and compiler-let. The new
  1959. syntactic definition for let* makes the value optional:
  1960.  
  1961. [Special Form]
  1962. let* ({var | (var [value])}*) {declaration}* {form}*
  1963.  
  1964. This changes let* to allow a list (var) to appear, meaning the same as simply
  1965. var.
  1966. [change_end]
  1967.  
  1968. [old_change_begin]
  1969.  
  1970. [Special Form]
  1971. compiler-let ({var | (var value)}*) {form}*
  1972.  
  1973. When executed by the Lisp interpreter, compiler-let behaves exactly like let
  1974. with all the variable bindings implicitly declared special. When the compiler
  1975. processes this form, however, no code is compiled for the bindings; instead,
  1976. the processing of the body by the compiler (including, in particular, the
  1977. expansion of any macro calls within the body) is done with the special
  1978. variables bound to the indicated values in the execution context of the
  1979. compiler. This is primarily useful for communication among complicated macros.
  1980.  
  1981. Declarations may not appear at the beginning of the body of a compiler-let.
  1982.  
  1983. -------------------------------------------------------------------------------
  1984. Rationale: Because of the unorthodox handling by compiler-let of its variable
  1985. bindings, it would be complicated and confusing to permit declarations that
  1986. apparently referred to the variables bound by compiler-let. Disallowing
  1987. declarations eliminates the problem.
  1988. -------------------------------------------------------------------------------
  1989.  
  1990. X3J13 voted in January 1989 (VARIABLE-LIST-ASYMMETRY)   to regularize the
  1991. binding formats for do, do*, let, let*, prog, prog*, and compiler-let. The new
  1992. syntactic definition for compiler-let makes the value optional:
  1993.  
  1994. [Macro]
  1995. compiler-let ({var | (var [value])}*) {form}*
  1996.  
  1997. This changes compiler-let to allow a list (var) to appear, meaning the same as
  1998. simply var.
  1999. [old_change_end]
  2000.  
  2001. [change_begin]
  2002. X3J13 voted in June 1989 (COMPILER-LET-CONFUSION)   to remove compiler-let from
  2003. the language. Many uses of compiler-let can be replaced with more portable code
  2004. that uses macrolet or symbol-macrolet.
  2005. [change_end]
  2006.  
  2007. [Special Form]
  2008. progv symbols values {form}*
  2009.  
  2010. progv is a special form that allows binding one or more dynamic variables whose
  2011. names may be determined at run time. The sequence of forms (an implicit progn)
  2012. is evaluated with the dynamic variables whose names are in the list symbols
  2013. bound to corresponding values from the list values. (If too few values are
  2014. supplied, the remaining symbols are bound and then made to have no value; see
  2015. makunbound. If too many values are supplied, the excess values are ignored.)
  2016. The results of the progv form are those of the last form. The bindings of the
  2017. dynamic variables are undone on exit from the progv form. The lists of symbols
  2018. and values are computed quantities; this is what makes progv different from,
  2019. for example, let, where the variable names are stated explicitly in the program
  2020. text.
  2021.  
  2022. progv is particularly useful for writing interpreters for languages embedded in
  2023. Lisp; it provides a handle on the mechanism for binding dynamic variables.
  2024.  
  2025. [Special Form]
  2026.  
  2027. flet ({(name lambda-list
  2028.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2029.      {form}*
  2030. labels ({(name lambda-list
  2031.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2032.      {form}*
  2033. macrolet ({(name varlist
  2034.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2035.      {form}*
  2036.  
  2037. flet may be used to define locally named functions. Within the body of the flet
  2038. form, function names matching those defined by the flet refer to the locally
  2039. defined functions rather than to the global function definitions of the same
  2040. name.
  2041.  
  2042. Any number of functions may be simultaneously defined. Each definition is
  2043. similar in format to a defun form: first a name, then a parameter list (which
  2044. may contain &optional, &rest, or &key parameters), then optional declarations
  2045. and documentation string, and finally a body.
  2046.  
  2047. (flet ((safesqrt (x) (sqrt (abs x))))
  2048.   ;; The safesqrt function is used in two places.
  2049.   (safesqrt (apply #'+ (map 'list #'safesqrt longlist))))
  2050.  
  2051. The labels construct is identical in form to the flet construct. These
  2052. constructs differ in that the scope of the defined function names for flet
  2053. encompasses only the body, whereas for labels it encompasses the function
  2054. definitions themselves. That is, labels can be used to define mutually
  2055. recursive functions, but flet cannot. This distinction is useful. Using flet
  2056. one can locally redefine a global function name, and the new definition can
  2057. refer to the global definition; the same construction using labels would not
  2058. have that effect.
  2059.  
  2060. (defun integer-power (n k)       ;A highly "bummed" integer
  2061.   (declare (integer n))          ; exponentiation routine
  2062.   (declare (type (integer 0 *) k))
  2063.   (labels ((expt0 (x k a)
  2064.              (declare (integer x a) (type (integer 0 *) k))
  2065.              (cond ((zerop k) a)
  2066.                    ((evenp k) (expt1 (* x x) (floor k 2) a))
  2067.                    (t (expt0 (* x x) (floor k 2) (* x a)))))
  2068.            (expt1 (x k a)
  2069.              (declare (integer x a) (type (integer 1 *) k))
  2070.              (cond ((evenp k) (expt1 (* x x) (floor k 2) a))
  2071.                    (t (expt0 (* x x) (floor k 2) (* x a))))))
  2072.     (expt0 n k 1)))
  2073.  
  2074. macrolet is similar in form to flet but defines local macros, using the same
  2075. format used by defmacro. The names established by macrolet as names for macros
  2076. are lexically scoped.
  2077.  
  2078. [change_begin]
  2079. I have observed that, while most Common Lisp users pronounce macrolet to rhyme
  2080. with ``silhouette,'' a small but vocal minority pronounce it to rhyme with
  2081. ``Chevrolet.'' A very few extremists furthermore adjust their pronunciation of
  2082. flet similarly: they say ``flay.'' Hey, hey! Tr鑚 outré.
  2083. [change_end]
  2084.  
  2085. Macros often must be expanded at ``compile time'' (more generally, at a time
  2086. before the program itself is executed), and so the run-time values of variables
  2087. are not available to macros defined by macrolet.
  2088.  
  2089. [old_change_begin]
  2090. The precise rule is that the macro-expansion functions defined by macrolet are
  2091. defined in the global environment; lexically scoped entities that would
  2092. ordinarily be lexically apparent are not visible within the expansion
  2093. functions.
  2094. [old_change_end]
  2095.  
  2096. [change_begin]
  2097. X3J13 voted in March 1989 (DEFINING-MACROS-NON-TOP-LEVEL)   to retract the
  2098. previous sentence and specify that the macro-expansion functions created by
  2099. macrolet are defined in the lexical environment in which the macrolet form
  2100. appears, not in the null lexical environment. Declarations, macrolet
  2101. definitions, and symbol-macrolet definitions affect code within the expansion
  2102. functions in a macrolet, but the consequences are undefined if such code
  2103. attempts to refer to any local variable or function bindings that are visible
  2104. in that lexical environment.
  2105. [change_end]
  2106.  
  2107. However, lexically scoped entities are visible within the body of the macrolet
  2108. form and are visible to the code that is the expansion of a macro call. The
  2109. following example should make this clear:
  2110.  
  2111. ;;; Example of scoping in macrolet.
  2112.  
  2113. (defun foo (x flag)
  2114.   (macrolet ((fudge (z)
  2115.                 ;;The parameters x and flag are not accessible
  2116.                 ;; at this point; a reference to flag would be to
  2117.                 ;; the global variable of that name.
  2118.                 `(if flag
  2119.                      (* ,z ,z)
  2120.                      ,z)))
  2121.     ;;The parameters x and flag are accessible here.
  2122.     (+ x
  2123.        (fudge x)
  2124.        (fudge (+ x 1)))))
  2125.  
  2126. The body of the macrolet becomes
  2127.  
  2128. (+ x
  2129.    (if flag
  2130.        (* x x)
  2131.        x))
  2132.    (if flag
  2133.        (* (+ x 1) (+ x 1))
  2134.        (+ x 1)))
  2135.  
  2136. after macro expansion. The occurrences of x and flag legitimately refer to the
  2137. parameters of the function foo because those parameters are visible at the site
  2138. of the macro call which produced the expansion.
  2139.  
  2140. [change_begin]
  2141. X3J13 voted in March 1988 (FLET-IMPLICIT-BLOCK)   to specify that the body of
  2142. each function or expander function defined by flet, labels, or macrolet is
  2143. implicitly enclosed in a block construct whose name is the same as the name of
  2144. the function. Therefore return-from may be used to exit from the function.
  2145.  
  2146. X3J13 voted in March 1989 (FUNCTION-NAME)   to extend flet and labels to accept
  2147. any function-name (a symbol or a list whose car is setf-see section 7.1) as a
  2148. name for a function to be locally defined. In this way one can create local
  2149. definitions for setf expansion functions. (X3J13 explicitly declined to extend
  2150. macrolet in the same manner.)
  2151.  
  2152. X3J13 voted in March 1988 (FLET-DECLARATIONS)   to change flet, labels, and
  2153. macrolet to allow declarations to appear before the body. The new descriptions
  2154. are therefore as follows:
  2155.  
  2156. [Special Form]
  2157.  
  2158. flet ({(name lambda-list
  2159.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2160.      {declaration}* {form}*
  2161. labels ({(name lambda-list
  2162.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2163.      {declaration}* {form}*
  2164. macrolet ({(name varlist
  2165.          [[ {declaration}* | doc-string ]] {form}*)}*)
  2166.      {declaration}* {form}*
  2167.  
  2168. These are now syntactically more similar to such other binding forms as let.
  2169.  
  2170. For flet and labels, the bodies of the locally defined functions are part of
  2171. the scope of pervasive declarations appearing before the main body. (This is
  2172. consistent with the treatment of initialization forms in let.) For macrolet,
  2173. however, the bodies of the locally defined macro expander functions are not
  2174. included in the scope of pervasive declarations appearing before the main body.
  2175. (This is consistent with the rule, stated below, that the bodies of macro
  2176. expander functions are in the global environment, not the local lexical
  2177. environment.) Here is an example:
  2178.  
  2179. (flet ((stretch (x) (* x *stretch-factor*))
  2180.        (chop (x) (- x *chop-margin*)))
  2181.   (declare (inline stretch chop))   ;Illegal in original Common Lisp
  2182.   (if (> x *chop-margin*) (stretch (chop x)) (chop (stretch x))))
  2183.  
  2184. X3J13 voted to permit declarations of the sort noted above.
  2185. [change_end]
  2186.  
  2187. [change_begin]
  2188.  
  2189. [Special Form]
  2190.  
  2191. symbol-macrolet ({(var expansion)}*)
  2192.                   {declaration}* {form}*
  2193.  
  2194. X3J13 voted in June 1988 (CLOS) to adopt the Common Lisp Object System. Part of
  2195. this proposal is a general mechanism, symbol-macrolet, for treating certain
  2196. variable names as if they were parameterless macro calls. This facility may be
  2197. useful independent of CLOS. X3J13 voted in March 1989
  2198. (SYMBOL-MACROLET-SEMANTICS)   to modify the definition of symbol-macrolet
  2199. substantially and also voted (SYMBOL-MACROLET-DECLARE)   to allow declarations
  2200. before the body of symbol-macrolet but with peculiar treatment of special and
  2201. type declarations.
  2202.  
  2203. The forms are executed as an implicit progn in a lexical environment that
  2204. causes every reference to any defined var to be replaced by the corresponding
  2205. expansion. It is as if the reference to the var were a parameterless macro
  2206. call; the expansion is evaluated or otherwise processed in place of the
  2207. reference (in particular, the expansion form is itself subject to further
  2208. expansion-this is one of the changes (SYMBOL-MACROLET-SEMANTICS)   from the
  2209. original definition in the CLOS proposal). Note, however, that the names of
  2210. such symbol macros occupy the name space of variables, not the name space of
  2211. functions; just as one may have a function (or macro, or special form) and a
  2212. variable with the same name without interference, so one may have an ordinary
  2213. macro (or function, or special form) and a symbol macro with the same name. The
  2214. use of symbol-macrolet can therefore be shadowed by let or other constructs
  2215. that bind variables; symbol-macrolet does not substitute for all occurrences of
  2216. a var as a variable but only for those occurrences that would be construed as
  2217. references in the scope of a lexical binding of var as a variable. For example:
  2218.  
  2219. (symbol-macrolet ((pollyanna 'goody))
  2220.   (list pollyanna (let ((pollyanna 'two-shoes)) pollyanna)))
  2221.  => (goody two-shoes), not (goody goody)
  2222.  
  2223. One might think that 'goody simply replaces all occurrences of pollyanna, and
  2224. so the value of the let would be goody; but this is not so. A little reflection
  2225. shows that under this incorrect interpretation the body in expanded form would
  2226. be
  2227.  
  2228. (list 'goody (let (('goody 'two-shoes)) 'goody))
  2229.  
  2230. which is syntactically malformed. The correct expanded form is
  2231.  
  2232. (list 'goody (let ((pollyanna 'two-shoes)) pollyanna))
  2233.  
  2234. because the rebinding of pollyanna by the let form shadows the symbol macro
  2235. definition.
  2236.  
  2237. The expansion for each var is not evaluated at binding time but only after it
  2238. has replaced a reference to the var. The setf macro allows a symbol macro to be
  2239. used as a place, in which case its expansion is used; moreover, setq of a
  2240. variable that is really a symbol macro will be treated as if setf had been
  2241. used. The values of the last form are returned, or nil if there is no value.
  2242.  
  2243. See macroexpand and macroexpand-1; they will expand symbol macros as well as
  2244. ordinary macros.
  2245.  
  2246. Certain declarations before the body are handled in a peculiar manner; see
  2247. section 9.1.
  2248. [change_end]
  2249.  
  2250. -------------------------------------------------------------------------------
  2251.  
  2252. 7.6. Conditionals
  2253.  
  2254. The traditional conditional construct in Lisp is cond. However, if is much
  2255. simpler and is directly comparable to conditional constructs in other
  2256. programming languages, so it is considered to be primitive in Common Lisp and
  2257. is described first. Common Lisp also provides the dispatching constructs case
  2258. and typecase, which are often more convenient than cond.
  2259.  
  2260. [Special Form]
  2261. if test then [else]
  2262.  
  2263. The if special form corresponds to the if-then-else construct found in most
  2264. algebraic programming languages. First the form test is evaluated. If the
  2265. result is not nil, then the form then is selected; otherwise the form else is
  2266. selected. Whichever form is selected is then evaluated, and if returns whatever
  2267. is returned by evaluation of the selected form.
  2268.  
  2269. (if test then else) == (cond (test then) (t else))
  2270.  
  2271. but if is considered more readable in some situations.
  2272.  
  2273. The else form may be omitted, in which case if the value of test is nil then
  2274. nothing is done and the value of the if form is nil. If the value of the if
  2275. form is important in this situation, then the and construct may be
  2276. stylistically preferable, depending on the context. If the value is not
  2277. important, but only the effect, then the when construct may be stylistically
  2278. preferable.
  2279.  
  2280. [Macro]
  2281. when test {form}*
  2282.  
  2283. (when test form1 form2 ... ) first evaluates test. If the result is nil, then
  2284. no form is evaluated, and nil is returned. Otherwise the forms constitute an
  2285. implicit progn and are evaluated sequentially from left to right, and the value
  2286. of the last one is returned.
  2287.  
  2288. (when p a b c) == (and p (progn a b c))
  2289. (when p a b c) == (cond (p a b c))
  2290. (when p a b c) == (if p (progn a b c) nil)
  2291. (when p a b c) == (unless (not p) a b c)
  2292.  
  2293. As a matter of style, when is normally used to conditionally produce some side
  2294. effects, and the value of the when form is normally not used. If the value is
  2295. relevant, then it may be stylistically more appropriate to use and or if.
  2296.  
  2297. [Macro]
  2298. unless test {form}*
  2299.  
  2300. (unless test form1 form2 ... ) first evaluates test. If the result is not nil,
  2301. then the forms are not evaluated, and nil is returned. Otherwise the forms
  2302. constitute an implicit progn and are evaluated sequentially from left to right,
  2303. and the value of the last one is returned.
  2304.  
  2305. (unless p a b c) == (cond ((not p) a b c))
  2306. (unless p a b c) == (if p nil (progn a b c))
  2307. (unless p a b c) == (when (not p) a b c)
  2308.  
  2309. As a matter of style, unless is normally used to conditionally produce some
  2310. side effects, and the value of the unless form is normally not used. If the
  2311. value is relevant, then it may be stylistically more appropriate to use if.
  2312.  
  2313. [Macro]
  2314. cond {(test {form}*)}*
  2315.  
  2316. A cond form has a number (possibly zero) of clauses, which are lists of forms.
  2317. Each clause consists of a test followed by zero or more consequents. For
  2318. example:
  2319.  
  2320. (cond (test-1 consequent-1-1 consequent-1-2 ...)
  2321.       (test-2)
  2322.       (test-3 consequent-3-1 ...)
  2323.       ... )
  2324.  
  2325. The first clause whose test evaluates to non-nil is selected; all other clauses
  2326. are ignored, and the consequents of the selected clause are evaluated in order
  2327. (as an implicit progn).
  2328.  
  2329. More specifically, cond processes its clauses in order from left to right. For
  2330. each clause, the test is evaluated. If the result is nil, cond advances to the
  2331. next clause. Otherwise, the cdr of the clause is treated as a list of forms, or
  2332. consequents; these forms are evaluated in order from left to right, as an
  2333. implicit progn. After evaluating the consequents, cond returns without
  2334. inspecting any remaining clauses. The cond special form returns the results of
  2335. evaluating the last of the selected consequents; if there were no consequents
  2336. in the selected clause, then the single (and necessarily non-null) value of the
  2337. test is returned. If cond runs out of clauses (every test produced nil, and
  2338. therefore no clause was selected), the value of the cond form is nil.
  2339.  
  2340. If it is desired to select the last clause unconditionally if all others fail,
  2341. the standard convention is to use t for the test. As a matter of style, it is
  2342. desirable to write a last clause (t nil) if the value of the cond form is to be
  2343. used for something. Similarly, it is in questionable taste to let the last
  2344. clause of a cond be a ``singleton clause''; an explicit t should be provided.
  2345. (Note moreover that (cond ... (x)) may behave differently from (cond ... (t x))
  2346. if x might produce multiple values; the former always returns a single value,
  2347. whereas the latter returns whatever values x returns. However, as a matter of
  2348. style it is preferable to obtain this behavior by writing (cond ... (t (values
  2349. x))), using the values function explicitly to indicate the discarding of any
  2350. excess values.) For example:
  2351.  
  2352. (setq z (cond (a 'foo) (b 'bar)))          ;Possibly confusing
  2353. (setq z (cond (a 'foo) (b 'bar) (t nil)))  ;Better
  2354. (cond (a b) (c d) (e))                     ;Possibly confusing
  2355. (cond (a b) (c d) (t e))                   ;Better
  2356. (cond (a b) (c d) (t (values e)))          ;Better (if one value
  2357.                                            ; needed)
  2358. (cond (a b) (c))                           ;Possibly confusing
  2359. (cond (a b) (t c))                         ;Better
  2360. (if a b c)                                 ;Also better
  2361.  
  2362. A Lisp cond form may be compared to a continued if-then-else as found in many
  2363. algebraic programming languages:
  2364.  
  2365. (cond (p ...)                            if p then ...
  2366.       (q ...)            roughly         else if q then ...
  2367.       (r ...)          corresponds       else if r then ...
  2368.       ...                   to           ...
  2369.       (t ...))                           else ...
  2370.  
  2371. [Macro]
  2372. case keyform {({({key}*) | key} {form}*)}*
  2373.  
  2374. case is a conditional that chooses one of its clauses to execute by comparing a
  2375. value to various constants, which are typically keyword symbols, integers, or
  2376. characters (but may be any objects). Its form is as follows:
  2377.  
  2378. (case keyform
  2379.   (keylist-1 consequent-1-1 consequent-1-2 ...)
  2380.   (keylist-2 consequent-2-1 ...)
  2381.   (keylist-3 consequent-3-1 ...)
  2382.   ...)
  2383.  
  2384. Structurally case is much like cond, and it behaves like cond in selecting one
  2385. clause and then executing all consequents of that clause. However, case differs
  2386. in the mechanism of clause selection.
  2387.  
  2388. The first thing case does is to evaluate the form keyform to produce an object
  2389. called the key object. Then case considers each of the clauses in turn. If key
  2390. is in the keylist (that is, is eql to any item in the keylist) of a clause, the
  2391. consequents of that clause are evaluated as an implicit progn; case returns
  2392. what was returned by the last consequent (or nil if there are no consequents in
  2393. that clause). If no clause is satisfied, case returns nil.
  2394.  
  2395. The keys in the keylists are not evaluated; literal key values must appear in
  2396. the keylists. It is an error for the same key to appear in more than one
  2397. clause; a consequence is that the order of the clauses does not affect the
  2398. behavior of the case construct.
  2399.  
  2400. Instead of a keylist, one may write one of the symbols t and otherwise. A
  2401. clause with such a symbol always succeeds and must be the last clause (this is
  2402. an exception to the order-independence of clauses). See also ecase and ccase,
  2403. each of which provides an implicit otherwise clause to signal an error if no
  2404. clause is satisfied.
  2405.  
  2406. If there is only one key for a clause, then that key may be written in place of
  2407. a list of that key, provided that no ambiguity results. Such a ``singleton
  2408. key'' may not be nil (which is confusable with (), a list of no keys), t,
  2409. otherwise, or a cons.
  2410.  
  2411. -------------------------------------------------------------------------------
  2412. Compatibility note: The Lisp Machine Lisp caseq construct uses eq for the
  2413. comparison. In Lisp Machine Lisp caseq therefore works for fixnums but not
  2414. bignums. The MacLisp caseq construct simply prohibits the use of bignums;
  2415. indeed, it permits only fixnums and symbols as clause keys. In the interest of
  2416. hiding the fixnum-bignum distinction, and for general language consistency,
  2417. case uses eql in Common Lisp.
  2418.  
  2419. The Interlisp selectq construct is similar to case.
  2420. -------------------------------------------------------------------------------
  2421.  
  2422. [Macro]
  2423. typecase keyform {(type {form}*)}*
  2424.  
  2425. typecase is a conditional that chooses one of its clauses by examining the type
  2426. of an object. Its form is as follows:
  2427.  
  2428. (typecase keyform
  2429.   (type-1 consequent-1-1 consequent-1-2 ...)
  2430.   (type-2 consequent-2-1 ...)
  2431.   (type-3 consequent-3-1 ...)
  2432.   ...)
  2433.  
  2434. Structurally typecase is much like cond or case, and it behaves like them in
  2435. selecting one clause and then executing all consequents of that clause. It
  2436. differs in the mechanism of clause selection.
  2437.  
  2438. The first thing typecase does is to evaluate the form keyform to produce an
  2439. object called the key object. Then typecase considers each of the clauses in
  2440. turn. The type that appears in each clause is a type specifier; it is not
  2441. evaluated but is a literal type specifier. The first clause for which the key
  2442. is of that clause's specified type is selected, the consequents of this clause
  2443. are evaluated as an implicit progn, and typecase returns what was returned by
  2444. the last consequent (or nil if there are no consequents in that clause). If no
  2445. clause is satisfied, typecase returns nil.
  2446.  
  2447. As for case, the symbol t or otherwise may be written for type to indicate that
  2448. the clause should always be selected. See also etypecase and ctypecase, each of
  2449. which provides an implicit otherwise clause to signal an error if no clause is
  2450. satisfied.
  2451.  
  2452. It is permissible for more than one clause to specify a given type,
  2453. particularly if one is a subtype of another; the earliest applicable clause is
  2454. chosen. Thus for typecase, unlike case, the order of the clauses may affect the
  2455. behavior of the construct. For example:
  2456.  
  2457. (typecase an-object
  2458.    (string ...)            ;This clause handles strings
  2459.    ((array t) ...)         ;This clause handles general arrays
  2460.    ((array bit) ...)       ;This clause handles bit arrays
  2461.    (array ...)             ;This handles all other arrays
  2462.    ((or list number) ...)  ;This handles lists and numbers
  2463.    (t ...))                ;This handles all other objects
  2464.  
  2465. A Common Lisp compiler may choose to issue a warning if a clause cannot be
  2466. selected because it is completely shadowed by earlier clauses.
  2467.  
  2468. -------------------------------------------------------------------------------
  2469.  
  2470. 7.7. Blocks and Exits
  2471.  
  2472. The block and return-from constructs provide a structured lexical non-local
  2473. exit facility. At any point lexically within a block construct, a return-from
  2474. with the same name may be used to perform an immediate transfer of control that
  2475. exits from the block. In the most common cases this mechanism is more efficient
  2476. than the dynamic non-local exit facility provided by catch and throw, described
  2477. in section 7.11.
  2478.  
  2479. [Special Form]
  2480. block name {form}*
  2481.  
  2482. The block construct executes each form from left to right, returning whatever
  2483. is returned by the last form. If, however, a return or return-from form that
  2484. specifies the same name is executed during the execution of some form, then the
  2485. results specified by the return or return-from are immediately returned as the
  2486. value of the block construct, and execution proceeds as if the block had
  2487. terminated normally. In this, block differs from progn; the progn construct has
  2488. nothing to do with return.
  2489.  
  2490. The name is not evaluated; it must be a symbol. The scope of the name is
  2491. lexical; only a return or return-from textually contained in some form can exit
  2492. from the block. The extent of the name is dynamic. Therefore it is only
  2493. possible to exit from a given run-time incarnation of a block once, either
  2494. normally or by explicit return.
  2495.  
  2496. The defun form implicitly puts a block around the body of the function defined;
  2497. the block has the same name as the function. Therefore one may use return-from
  2498. to return prematurely from a function defined by defun.
  2499.  
  2500. The lexical scoping of the block name is fully general and has consequences
  2501. that may be surprising to users and implementors of other Lisp systems. For
  2502. example, the return-from in the following example actually does work in Common
  2503. Lisp as one might expect:
  2504.  
  2505. (block loser
  2506.    (catch 'stuff
  2507.       (mapcar #'(lambda (x) (if (numberp x)
  2508.                                 (hairyfun x)
  2509.                                 (return-from loser nil)))
  2510.               items)))
  2511.  
  2512. Depending on the situation, a return in Common Lisp may not be simple. A return
  2513. can break up catchers if necessary to get to the block in question. It is
  2514. possible for a ``closure'' created by function for a lambda-expression to refer
  2515. to a block name as long as the name is lexically apparent.
  2516.  
  2517. [Special Form]
  2518. return-from name [result]
  2519.  
  2520. return-from is used to return from a block or from such constructs as do and
  2521. prog that implicitly establish a block. The name is not evaluated and must be a
  2522. symbol. A block construct with the same name must lexically enclose the
  2523. occurrence of return-from; whatever the evaluation of result produces is
  2524. immediately returned from the block. (If the result form is omitted, it
  2525. defaults to nil. As a matter of style, this form ought to be used to indicate
  2526. that the particular value returned doesn't matter.)
  2527.  
  2528. The return-from form itself never returns and cannot have a value; it causes
  2529. results to be returned from a block construct. If the evaluation of result
  2530. produces multiple values, those multiple values are returned by the construct
  2531. exited.
  2532.  
  2533. [Macro]
  2534. return [result]
  2535.  
  2536. (return form) is identical in meaning to (return-from nil form); it returns
  2537. from a block named nil. Blocks established implicitly by iteration constructs
  2538. such as do are named nil, so that return will exit properly from such a
  2539. construct.
  2540.  
  2541. -------------------------------------------------------------------------------
  2542.  
  2543. 7.8. Iteration
  2544.  
  2545. Common Lisp provides a number of iteration constructs. The loop construct
  2546. provides a trivial iteration facility; it is little more than a progn with a
  2547. branch from the bottom back to the top. The do and do* constructs provide a
  2548. general iteration facility for controlling the variation of several variables
  2549. on each cycle. For specialized iterations over the elements of a list or n
  2550. consecutive integers, dolist and dotimes are provided. The tagbody construct is
  2551. the most general, permitting arbitrary go statements within it. (The
  2552. traditional prog construct is a synthesis of tagbody, block, and let.) Most of
  2553. the iteration constructs permit statically defined non-local exits (see
  2554. return-from and return).
  2555.  
  2556. -------------------------------------------------------------------------------
  2557.  
  2558.    *  Indefinite Iteration
  2559.    *  General Iteration
  2560.    *  Simple Iteration Constructs
  2561.    *  Mapping
  2562.    *  The ``Program Feature''
  2563.  
  2564. -------------------------------------------------------------------------------
  2565.  
  2566. 7.8.1. Indefinite Iteration
  2567.  
  2568. The loop construct is the simplest iteration facility. It controls no
  2569. variables, and simply executes its body repeatedly.
  2570.  
  2571. [Macro]
  2572. loop {form}*
  2573.  
  2574. Each form is evaluated in turn from left to right. When the last form has been
  2575. evaluated, then the first form is evaluated again, and so on, in a never-ending
  2576. cycle. The loop construct never returns a value. Its execution must be
  2577. terminated explicitly, using return or throw, for example.
  2578.  
  2579. loop, like most iteration constructs, establishes an implicit block named nil.
  2580. Thus return may be used to exit from a loop with specified results.
  2581.  
  2582. [old_change_begin]
  2583. A loop construct has this meaning only if every form is non-atomic (a list).
  2584. The case where some form is atomic is reserved for future extensions.
  2585.  
  2586. -------------------------------------------------------------------------------
  2587. Implementation note: There have been several proposals for a powerful iteration
  2588. mechanism to be called loop. One version is provided in Lisp Machine Lisp.
  2589. Implementors are encouraged to experiment with extensions to the loop syntax,
  2590. but users should be advised that in all likelihood some specific set of
  2591. extensions to loop will be adopted in a future revision of Common Lisp.
  2592. -------------------------------------------------------------------------------
  2593.  
  2594. [old_change_end]
  2595.  
  2596. [change_begin]
  2597. X3J13 voted in January 1989 (LOOP-FACILITY)   to include just such an extension
  2598. of loop. See chapter 26.
  2599. [change_end]
  2600.  
  2601. -------------------------------------------------------------------------------
  2602.  
  2603. 7.8.2. General Iteration
  2604.  
  2605. In contrast to loop, do and do* provide a powerful and general mechanism for
  2606. repetitively recalculating many variables.
  2607.  
  2608. [Macro]
  2609.  
  2610. do ({(var [init [step]])}*)
  2611.    (end-test {result}*)
  2612.    {declaration}* {tag | statement}*
  2613. do* ({(var [init [step]])}*)
  2614.    (end-test {result}*)
  2615.    {declaration}* {tag | statement}*
  2616.  
  2617. The do special form provides a generalized iteration facility, with an
  2618. arbitrary number of ``index variables.'' These variables are bound within the
  2619. iteration and stepped in parallel in specified ways. They may be used both to
  2620. generate successive values of interest (such as successive integers) or to
  2621. accumulate results. When an end condition is met, the iteration terminates with
  2622. a specified value.
  2623.  
  2624. In general, a do loop looks like this:
  2625.  
  2626. (do ((var1 init1 step1)
  2627.      (var2 init2 step2)
  2628.      ...
  2629.      (varn initn stepn))
  2630.     (end-test . result)
  2631.   {declaration}*
  2632.   . tagbody)
  2633.  
  2634. A do* loop looks exactly the same except that the name do is replaced by do*.
  2635.  
  2636. The first item in the form is a list of zero or more index-variable specifiers.
  2637. Each index-variable specifier is a list of the name of a variable var, an
  2638. initial value init, and a stepping form step. If init is omitted, it defaults
  2639. to nil. If step is omitted, the var is not changed by the do construct between
  2640. repetitions (though code within the do is free to alter the value of the
  2641. variable by using setq).
  2642.  
  2643. An index-variable specifier can also be just the name of a variable. In this
  2644. case, the variable has an initial value of nil and is not changed between
  2645. repetitions. As a matter of style, it is recommended that an unadorned variable
  2646. name be written only when that variable will be stored into (such as by setq)
  2647. before its first use. If it is important that the initial value be nil rather
  2648. than some undefined value, then it is clearer to write out (varj nil) if the
  2649. initial value is intended to mean ``false,'' or (varj '()) if the initial value
  2650. is intended to be an empty list.
  2651.  
  2652. [change_begin]
  2653. X3J13 voted in January 1989 (VARIABLE-LIST-ASYMMETRY)   to regularize the
  2654. binding formats for do, do*, let, let*, prog, prog*, and compiler-let. In the
  2655. case of do and do* the first edition was inconsistent; the formal syntax fails
  2656. to reflect the fact that a simple variable name may appear, as described in the
  2657. preceding paragraph. The definitions should read
  2658.  
  2659. [Macro]
  2660.  
  2661. do ({var | (var [init [step]])}*)
  2662.    (end-test {result}*)
  2663.    {declaration}* {tag | statement}*
  2664. do* ({var | (var [init [step]])}*)
  2665.    (end-test {result}*)
  2666.    {declaration}* {tag | statement}*
  2667.  
  2668. for consistency with the reading of the first edition and the X3J13 vote.
  2669. [change_end]
  2670.  
  2671. Before the first iteration, all the init forms are evaluated, and each var is
  2672. bound to the value of its respective init. This is a binding, not an
  2673. assignment; when the loop terminates, the old values of those variables will be
  2674. restored. For do, all of the init forms are evaluated before any var is bound;
  2675. hence all the init forms may refer to the old bindings of all the variables
  2676. (that is, to the values visible before beginning execution of the do
  2677. construct). For do*, the first init form is evaluated, then the first var is
  2678. bound to that value, then the second init form is evaluated, then the second
  2679. var is bound, and so on; in general, the initj form can refer to the new
  2680. binding vark if k < j, and otherwise to the old binding of vark.
  2681.  
  2682. The second element of the loop is a list of an end-testing predicate form
  2683. end-test and zero or more result forms. This resembles a cond clause. At the
  2684. beginning of each iteration, after processing the variables, the end-test is
  2685. evaluated. If the result is nil, execution proceeds with the body of the do (or
  2686. do*) form. If the result is not nil, the result forms are evaluated in order as
  2687. an implicit progn,   and then do returns. do returns the results of evaluating
  2688. the last result form. If there are no result forms, the value of do is nil.
  2689. Note that this is not quite analogous to the treatment of clauses in a cond
  2690. form, because a cond clause with no result forms returns the (non-nil) result
  2691. of the test.
  2692.  
  2693. At the beginning of each iteration other than the first, the index variables
  2694. are updated as follows. All the step forms are evaluated, from left to right,
  2695. and the resulting values are assigned to the respective index variables. Any
  2696. variable that has no associated step form is not assigned to. For do, all the
  2697. step forms are evaluated before any variable is updated; the assignment of
  2698. values to variables is done in parallel, as if by psetq. Because all of the
  2699. step forms are evaluated before any of the variables are altered, a step form
  2700. when evaluated always has access to the old values of all the index variables,
  2701. even if other step forms precede it. For do*, the first step form is evaluated,
  2702. then the value is assigned to the first var, then the second step form is
  2703. evaluated, then the value is assigned to the second var, and so on; the
  2704. assignment of values to variables is done sequentially, as if by setq. For
  2705. either do or do*, after the variables have been updated, the end-test is
  2706. evaluated as described above, and the iteration continues.
  2707.  
  2708. If the end-test of a do form is nil, the test will never succeed. Therefore
  2709. this provides an idiom for ``do forever'': the body of the do is executed
  2710. repeatedly, stepping variables as usual. (The loop construct performs a ``do
  2711. forever'' that steps no variables.) The infinite loop can be terminated by the
  2712. use of return, return-from, go to an outer level, or throw. For example:
  2713.  
  2714. (do ((j 0 (+ j 1)))
  2715.     (nil)                        ;Do forever
  2716.   (format t "~%Input ~D:" j)
  2717.   (let ((item (read)))
  2718.     (if (null item) (return)     ;Process items until nil seen
  2719.         (format t "~&Output ~D: ~S" j (process item)))))
  2720.  
  2721. The remainder of the do form constitutes an implicit tagbody. Tags may appear
  2722. within the body of a do loop for use by go statements appearing in the body
  2723. (but such go statements may not appear in the variable specifiers, the
  2724. end-test, or the result forms). When the end of a do body is reached, the next
  2725. iteration cycle (beginning with the evaluation of step forms) occurs.
  2726.  
  2727. An implicit block named nil surrounds the entire do form. A return statement
  2728. may be used at any point to exit the loop immediately.
  2729.  
  2730. declare forms may appear at the beginning of a do body. They apply to code in
  2731. the do body, to the bindings of the do variables, to the init forms, to the
  2732. step forms, to the end-test, and to the result forms.
  2733.  
  2734. -------------------------------------------------------------------------------
  2735. Compatibility note: ``Old-style'' MacLisp do loops, that is, those of the form
  2736. (do var init step end-test . body), are not supported in Common Lisp. Such
  2737. old-style loops are considered obsolete and in any case are easily converted to
  2738. a new-style do with the insertion of three pairs of parentheses. In practice
  2739. the compiler can catch nearly all instances of old-style do loops because they
  2740. will not have a legal format anyway.
  2741. -------------------------------------------------------------------------------
  2742.  
  2743. Here are some examples of the use of do:
  2744.  
  2745. (do ((i 0 (+ i 1))     ;Sets every null element of a-vector to zero
  2746.      (n (length a-vector)))
  2747.     ((= i n))
  2748.   (when (null (aref a-vector i))
  2749.     (setf (aref a-vector i) 0)))
  2750.  
  2751. The construction
  2752.  
  2753. (do ((x e (cdr x))
  2754.      (oldx x x))
  2755.     ((null x))
  2756.   body)
  2757.  
  2758. exploits parallel assignment to index variables. On the first iteration, the
  2759. value of oldx is whatever value x had before the do was entered. On succeeding
  2760. iterations, oldx contains the value that x had on the previous iteration.
  2761.  
  2762. Very often an iterative algorithm can be most clearly expressed entirely in the
  2763. step forms of a do, and the body is empty. For example,
  2764.  
  2765. (do ((x foo (cdr x))
  2766.      (y bar (cdr y))
  2767.      (z '() (cons (f (car x) (car y)) z)))
  2768.     ((or (null x) (null y))
  2769.      (nreverse z)))
  2770.  
  2771. does the same thing as (mapcar #'f foo bar). Note that the step computation for
  2772. z exploits the fact that variables are stepped in parallel. Also, the body of
  2773. the loop is empty. Finally, the use of nreverse to put an accumulated do loop
  2774. result into the correct order is a standard idiom. Another example:
  2775.  
  2776. (defun list-reverse (list)
  2777.        (do ((x list (cdr x))
  2778.             (y '() (cons (car x) y)))
  2779.            ((endp x) y)))
  2780.  
  2781. Note the use of endp rather than null or atom to test for the end of a list;
  2782. this may result in more robust code.
  2783.  
  2784. As an example of nested loops, suppose that env holds a list of conses. The car
  2785. of each cons is a list of symbols, and the cdr of each cons is a list of equal
  2786. length containing corresponding values. Such a data structure is similar to an
  2787. association list but is divided into ``frames''; the overall structure
  2788. resembles a rib cage. A lookup function on such a data structure might be
  2789.  
  2790. (defun ribcage-lookup (sym ribcage)
  2791.        (do ((r ribcage (cdr r)))
  2792.            ((null r) nil)
  2793.          (do ((s (caar r) (cdr s))
  2794.               (v (cdar r) (cdr v)))
  2795.              ((null s))
  2796.            (when (eq (car s) sym)
  2797.              (return-from ribcage-lookup (car v))))))
  2798.  
  2799. (Notice the use of indentation in the above example to set off the bodies of
  2800. the do loops.)
  2801.  
  2802. A do loop may be explained in terms of the more primitive constructs block,
  2803. return, let, loop, tagbody, and psetq as follows:
  2804.  
  2805. (block nil
  2806.   (let ((var1 init1)
  2807.         (var2 init2)
  2808.         ...
  2809.         (varn initn))
  2810.     {declaration}*
  2811.     (loop (when end-test (return (progn . result)))
  2812.           (tagbody . tagbody)
  2813.           (psetq var1 step1
  2814.                  var2 step2
  2815.                  ...
  2816.                  varn stepn))))
  2817.  
  2818. do* is exactly like do except that the bindings and steppings of the variables
  2819. are performed sequentially rather than in parallel. It is as if, in the above
  2820. explanation, let were replaced by let* and psetq were replaced by setq.
  2821.  
  2822. -------------------------------------------------------------------------------
  2823.  
  2824. 7.8.3. Simple Iteration Constructs
  2825.  
  2826. The constructs dolist and dotimes execute a body of code once for each value
  2827. taken by a single variable. They are expressible in terms of do, but capture
  2828. very common patterns of use.
  2829.  
  2830. Both dolist and dotimes perform a body of statements repeatedly. On each
  2831. iteration a specified variable is bound to an element of interest that the body
  2832. may examine. dolist examines successive elements of a list, and dotimes
  2833. examines integers from 0 to n-1 for some specified positive integer n.
  2834.  
  2835. The value of any of these constructs may be specified by an optional result
  2836. form, which if omitted defaults to the value nil.
  2837.  
  2838. The return statement may be used to return immediately from a dolist or dotimes
  2839. form, discarding any following iterations that might have been performed; in
  2840. effect, a block named nil surrounds the construct. The body of the loop is
  2841. implicitly a tagbody construct; it may contain tags to serve as the targets of
  2842. go statements. Declarations may appear before the body of the loop.
  2843.  
  2844. [Macro]
  2845.  
  2846. dolist (var listform [resultform])
  2847.        {declaration}* {tag | statement}*
  2848.  
  2849. dolist provides straightforward iteration over the elements of a list. First
  2850. dolist evaluates the form listform, which should produce a list. It then
  2851. executes the body once for each element in the list, in order, with the
  2852. variable var bound to the element. Then resultform (a single form, not an
  2853. implicit progn) is evaluated, and the result is the value of the dolist form.
  2854. (When the resultform is evaluated, the control variable var is still bound and
  2855. has the value nil.) If resultform is omitted, the result is nil.
  2856.  
  2857. (dolist (x '(a b c d)) (prin1 x) (princ " ")) => nil
  2858.    after printing ``a b c d '' (note the trailing space)
  2859.  
  2860. An explicit return statement may be used to terminate the loop and return a
  2861. specified value.
  2862.  
  2863. [change_begin]
  2864. X3J13 voted in January 1989 (MAPPING-DESTRUCTIVE-INTERACTION)   to restrict
  2865. user side effects; see section 7.9.
  2866. [change_end]
  2867.  
  2868. [Macro]
  2869.  
  2870. dotimes (var countform [resultform])
  2871.         {declaration}* {tag | statement}*
  2872.  
  2873. dotimes provides straightforward iteration over a sequence of integers. The
  2874. expression (dotimes (var countform resultform) . progbody) evaluates the form
  2875. countform, which should produce an integer. It then performs progbody once for
  2876. each integer from zero (inclusive) to count (exclusive), in order, with the
  2877. variable var bound to the integer; if the value of countform is zero or
  2878. negative, then the progbody is performed zero times. Finally, resultform (a
  2879. single form, not an implicit progn) is evaluated, and the result is the value
  2880. of the dotimes form. (When the resultform is evaluated, the control variable
  2881. var is still bound and has as its value the number of times the body was
  2882. executed.) If resultform is omitted, the result is nil.
  2883.  
  2884. An explicit return statement may be used to terminate the loop and return a
  2885. specified value.
  2886.  
  2887. Here is an example of the use of dotimes in processing strings:
  2888.  
  2889. ;;; True if the specified subsequence of the string is a
  2890. ;;; palindrome (reads the same forwards and backwards).
  2891.  
  2892. (defun palindromep (string &optional
  2893.                            (start 0)
  2894.                            (end (length string)))
  2895.   (dotimes (k (floor (- end start) 2) t)
  2896.     (unless (char-equal (char string (+ start k))
  2897.                         (char string (- end k 1)))
  2898.       (return nil))))
  2899.  
  2900. (palindromep "Able was I ere I saw Elba") => t
  2901.  
  2902. (palindromep "A man, a plan, a canal-Panama!") => nil
  2903.  
  2904. (remove-if-not #'alpha-char-p     ;Remove punctuation
  2905.                "A man, a plan, a canal-Panama!")
  2906.    => "AmanaplanacanalPanama"
  2907.  
  2908. (palindromep
  2909.  (remove-if-not #'alpha-char-p
  2910.                 "A man, a plan, a canal-Panama!")) => t
  2911.  
  2912. (palindromep
  2913.  (remove-if-not
  2914.    #'alpha-char-p
  2915.    "Unremarkable was I ere I saw Elba Kramer, nu?")) => t
  2916.  
  2917. (palindromep
  2918.  (remove-if-not
  2919.    #'alpha-char-p
  2920.    "A man, a plan, a cat, a ham, a yak,
  2921.                    a yam, a hat, a canal-Panama!")) => t
  2922.  
  2923. (palindromep
  2924.  (remove-if-not
  2925.    #'alpha-char-p
  2926.    "Ja-da, ja-da, ja-da ja-da jing jing jing")) => nil
  2927.  
  2928. Altering the value of var in the body of the loop (by using setq, for example)
  2929. will have unpredictable, possibly implementation-dependent results. A Common
  2930. Lisp compiler may choose to issue a warning if such a variable appears in a
  2931. setq.
  2932.  
  2933. -------------------------------------------------------------------------------
  2934. Compatbility note: The dotimes construct is the closest thing in Common Lisp to
  2935. the Interlisp rptq construct.
  2936. -------------------------------------------------------------------------------
  2937.  
  2938. See also do-symbols, do-external-symbols, and do-all-symbols.
  2939.  
  2940. -------------------------------------------------------------------------------
  2941.  
  2942. 7.8.4. Mapping
  2943.  
  2944. Mapping is a type of iteration in which a function is successively applied to
  2945. pieces of one or more sequences. The result of the iteration is a sequence
  2946. containing the respective results of the function applications. There are
  2947. several options for the way in which the pieces of the list are chosen and for
  2948. what is done with the results returned by the applications of the function.
  2949.  
  2950. The function map may be used to map over any kind of sequence. The following
  2951. functions operate only on lists.
  2952.  
  2953. [Function]
  2954.  
  2955. mapcar function list &rest more-lists
  2956. maplist function list &rest more-lists
  2957. mapc function list &rest more-lists
  2958. mapl function list &rest more-lists
  2959. mapcan function list &rest more-lists
  2960. mapcon function list &rest more-lists
  2961.  
  2962. For each of these mapping functions, the first argument is a function and the
  2963. rest must be lists. The function must take as many arguments as there are
  2964. lists.
  2965.  
  2966. mapcar operates on successive elements of the lists. First the function is
  2967. applied to the car of each list, then to the cadr of each list, and so on.
  2968. (Ideally all the lists are the same length; if not, the iteration terminates
  2969. when the shortest list runs out, and excess elements in other lists are
  2970. ignored.) The value returned by mapcar is a list of the results of the
  2971. successive calls to the function. For example:
  2972.  
  2973. (mapcar #'abs '(3 -4 2 -5 -6)) => (3 4 2 5 6)
  2974. (mapcar #'cons '(a b c) '(1 2 3)) => ((a . 1) (b . 2) (c . 3))
  2975.  
  2976. maplist is like mapcar except that the function is applied to the lists and
  2977. successive cdr's of those lists rather than to successive elements of the
  2978. lists. For example:
  2979.  
  2980. (maplist #'(lambda (x) (cons 'foo x))
  2981.          '(a b c d))
  2982.    => ((foo a b c d) (foo b c d) (foo c d) (foo d))
  2983.  
  2984. (maplist #'(lambda (x) (if (member (car x) (cdr x)) 0 1)))
  2985.          '(a b a c d b c))
  2986.    => (0 0 1 0 1 1 1)
  2987.    ;An entry is 1 if the corresponding element of the input
  2988.    ; list was the last instance of that element in the input list.
  2989.  
  2990. mapl and mapc are like maplist and mapcar, respectively, except that they do
  2991. not accumulate the results of calling the function.
  2992.  
  2993. -------------------------------------------------------------------------------
  2994. Compatibility note: In all Lisp systems since Lisp 1.5, mapl has been called
  2995. map. In the chapter on sequences it is explained why this was a bad choice.
  2996. Here the name map is used for the far more useful generic sequence mapper, in
  2997. closer accordance with the computer science literature, especially the growing
  2998. body of papers on functional programming. Note that this remark, predating the
  2999. design of the Common Lisp Object System, uses the term ``generic'' in a generic
  3000. sense and not necessarily in the technical sense used by CLOS (see chapter 2).
  3001. -------------------------------------------------------------------------------
  3002.  
  3003. These functions are used when the function is being called merely for its side
  3004. effects rather than for its returned values. The value returned by mapl or mapc
  3005. is the second argument, that is, the first sequence argument.
  3006.  
  3007. mapcan and mapcon are like mapcar and maplist, respectively, except that they
  3008. combine the results of the function using nconc instead of list. That is,
  3009.  
  3010. (mapcon f x1 ... xn)
  3011.    == (apply #'nconc (maplist f x1 ... xn))
  3012.  
  3013. and similarly for the relationship between mapcan and mapcar. Conceptually,
  3014. these functions allow the mapped function to return a variable number of items
  3015. to be put into the output list. This is particularly useful for effectively
  3016. returning zero or one item:
  3017.  
  3018. (mapcan #'(lambda (x) (and (numberp x) (list x)))
  3019.         '(a 1 b c 3 4 d 5))
  3020.    => (1 3 4 5)
  3021.  
  3022. In this case the function serves as a filter; this is a standard Lisp idiom
  3023. using mapcan. (The function remove-if-not might have been useful in this
  3024. particular context, however.) Remember that nconc is a destructive operation,
  3025. and therefore so are mapcan and mapcon; the lists returned by the function are
  3026. altered in order to concatenate them.
  3027.  
  3028. Sometimes a do or a straightforward recursion is preferable to a mapping
  3029. operation; however, the mapping functions should be used wherever they
  3030. naturally apply because this increases the clarity of the code.
  3031.  
  3032. The functional argument to a mapping function must be acceptable to apply; it
  3033. cannot be a macro or the name of a special form. Of course, there is nothing
  3034. wrong with using a function that has &optional and &rest parameters as the
  3035. functional argument.
  3036.  
  3037. [change_begin]
  3038. X3J13 voted in June 1988 (FUNCTION-TYPE)   to allow the function to be only of
  3039. type symbol or function; a lambda-expression is no longer acceptable as a
  3040. functional argument. One must use the function special form or the abbreviation
  3041. #' before a lambda-expression that appears as an explicit argument form.
  3042.  
  3043. X3J13 voted in January 1989 (MAPPING-DESTRUCTIVE-INTERACTION)   to restrict
  3044. user side effects; see section 7.9.
  3045. [change_end]
  3046.  
  3047. -------------------------------------------------------------------------------
  3048.  
  3049. 7.8.5. The ``Program Feature''
  3050.  
  3051. Lisp implementations since Lisp 1.5 have had what was originally called ``the
  3052. program feature,'' as if it were impossible to write programs without it! The
  3053. prog construct allows one to write in an Algol-like or Fortran-like
  3054. statement-oriented style, using go statements that can refer to tags in the
  3055. body of the prog. Modern Lisp programming style tends to use prog rather
  3056. infrequently. The various iteration constructs, such as do, have bodies with
  3057. the characteristics of a prog. (However, the ability to use go statements
  3058. within iteration constructs is very seldom called upon in practice.)
  3059.  
  3060. Three distinct operations are performed by prog: it binds local variables, it
  3061. permits use of the return statement, and it permits use of the go statement. In
  3062. Common Lisp, these three operations have been separated into three distinct
  3063. constructs: let, block, and tagbody. These three constructs may be used
  3064. independently as building blocks for other types of constructs.
  3065.  
  3066. [Special Form]
  3067. tagbody {tag | statement}*
  3068.  
  3069. The part of a tagbody after the variable list is called the body. An item in
  3070. the body may be a symbol or an integer, in which case it is called a tag, or an
  3071. item in the body may be a list, in which case it is called a statement.
  3072.  
  3073. Each element of the body is processed from left to right. A tag is ignored; a
  3074. statement is evaluated, and its results are discarded. If the end of the body
  3075. is reached, the tagbody returns nil.
  3076.  
  3077. If (go tag) is evaluated, control jumps to the part of the body labelled with
  3078. the tag.
  3079.  
  3080. -------------------------------------------------------------------------------
  3081. Compatibility note: The ``computed go'' feature of MacLisp is not supported.
  3082. The syntax of a computed go is idiosyncratic, and the feature is not supported
  3083. by Lisp Machine Lisp, NIL (New Implementation of Lisp), or Interlisp. The
  3084. computed go has been infrequently used in MacLisp anyway and is easily
  3085. simulated with no loss of efficiency by using a case statement each of whose
  3086. clauses performs a (non-computed) go.
  3087. -------------------------------------------------------------------------------
  3088.  
  3089. The scope of the tags established by a tagbody is lexical, and the extent is
  3090. dynamic. Once a tagbody construct has been exited, it is no longer legal to go
  3091. to a tag in its body. It is permissible for a go to jump to a tagbody that is
  3092. not the innermost tagbody construct containing that go; the tags established by
  3093. a tagbody will only shadow other tags of like name.
  3094.  
  3095. The lexical scoping of the go targets named by tags is fully general and has
  3096. consequences that may be surprising to users and implementors of other Lisp
  3097. systems. For example, the go in the following example actually does work in
  3098. Common Lisp as one might expect:
  3099.  
  3100. (tagbody
  3101.    (catch 'stuff
  3102.       (mapcar #'(lambda (x) (if (numberp x)
  3103.                                 (hairyfun x)
  3104.                                 (go lose)))
  3105.               items))
  3106.    (return)
  3107.  lose
  3108.    (error "I lost big!"))
  3109.  
  3110. Depending on the situation, a go in Common Lisp does not necessarily correspond
  3111. to a simple machine ``jump'' instruction. A go can break up catchers if
  3112. necessary to get to the target. It is possible for a ``closure'' created by
  3113. function for a lambda-expression to refer to a go target as long as the tag is
  3114. lexically apparent. See chapter 3 for an elaborate example of this.
  3115.  
  3116. [change_begin]
  3117. There are some holes in this specification (and that of go) that leave some
  3118. room for interpretation. For example, there is no explicit prohibition against
  3119. the same tag appearing more than once in the same tagbody body. Every
  3120. implementation I know of will complain in the compiler, if not in the
  3121. interpreter, if there is a go to such a duplicated tag; but some implementors
  3122. take the position that duplicate tags are permitted provided there is no go to
  3123. such a tag. (``If a tree falls in the forest, and there is no one there to hear
  3124. it, then no one needs to yell `Timber!''') Also, some implementations allow
  3125. objects other than symbols, integers, and lists in the body and typically
  3126. ignore them. Consequently, some programmers use redundant tags such as - for
  3127. formatting purposes, and strings as comments:
  3128.  
  3129. (defun dining-philosopher (j)
  3130.   (tagbody -
  3131.    think   (unless (hungry) (go think))
  3132.            -
  3133.            "Can't eat without chopsticks."
  3134.            (snatch (chopstick j))
  3135.            (snatch (chopstick (mod (+ j 1) 5)))
  3136.            -
  3137.    eat     (when (hungry)
  3138.              (mapc #'gobble-down
  3139.                    '(twice-cooked-pork kung-pao-chi-ding
  3140.                      wu-dip-har orange-flavor-beef
  3141.                      two-side-yellow-noodles twinkies))
  3142.              (go eat))
  3143.            -
  3144.            "Can't think with my neighbors' stomachs rumbling."
  3145.            (relinquish (chopstick j))
  3146.            (relinquish (chopstick (mod (+ j 1) 5)))
  3147.            -
  3148.            (if (happy) (go think)
  3149.                (become insurance-salesman))))
  3150.  
  3151. In certain implementations of Common Lisp they get away with it. Others abhor
  3152. what they view as an abuse of unintended ambiguity in the language
  3153. specification. For maximum portability, I advise users to steer clear of these
  3154. issues. Similarly, it is best to avoid using nil as a tag, even though it is a
  3155. symbol, because a few implementations treat nil as a list to be executed. To be
  3156. extra careful, avoid calling from within a tagbody a macro whose expansion
  3157. might not be a non-nil list; wrap such a call in (progn ...), or rewrite the
  3158. macro to return (progn ...) if possible.
  3159. [change_end]
  3160.  
  3161. [Macro]
  3162.  
  3163. prog ({var | (var [init])}*) {declaration}* {tag | statement}*
  3164. prog* ({var | (var [init])}*) {declaration}* {tag | statement}*
  3165.  
  3166. The prog construct is a synthesis of let, block, and tagbody, allowing bound
  3167. variables and the use of return and go within a single construct. A typical
  3168. prog construct looks like this:
  3169.  
  3170. (prog (var1 var2 (var3 init3) var4 (var5 init5))
  3171.       {declaration}*
  3172.       statement1
  3173.  tag1
  3174.       statement2
  3175.       statement3
  3176.       statement4
  3177.  tag2
  3178.       statement5
  3179.       ...
  3180.       )
  3181.  
  3182. The list after the keyword prog is a set of specifications for binding var1,
  3183. var2, etc., which are temporary variables bound locally to the prog. This list
  3184. is processed exactly as the list in a let statement: first all the init forms
  3185. are evaluated from left to right (where nil is used for any omitted init form),
  3186. and then the variables are all bound in parallel to the respective results. Any
  3187. declaration appearing in the prog is used as if appearing at the top of the let
  3188. body.
  3189.  
  3190. The body of the prog is executed as if it were a tagbody construct; the go
  3191. statement may be used to transfer control to a tag.
  3192.  
  3193. A prog implicitly establishes a block named nil around the entire prog
  3194. construct, so that return may be used at any time to exit from the prog
  3195. construct.
  3196.  
  3197. Here is a fine example of what can be done with prog:
  3198.  
  3199. (defun king-of-confusion (w)
  3200.   "Take a cons of two lists and make a list of conses.
  3201.    Think of this function as being like a zipper."
  3202.   (prog (x y z)     ;Initialize x, y, z to nil
  3203.         (setq y (car w) z (cdr w))
  3204.    loop
  3205.         (cond ((null y) (return x))
  3206.               ((null z) (go err)))
  3207.    rejoin
  3208.         (setq x (cons (cons (car y) (car z)) x))
  3209.         (setq y (cdr y) z (cdr z))
  3210.         (go loop)
  3211.    err
  3212.         (cerror "Will self-pair extraneous items"
  3213.                 "Mismatch - gleep!   S" y)
  3214.         (setq z y)
  3215.         (go rejoin)))
  3216.  
  3217. which is accomplished somewhat more perspicuously by
  3218.  
  3219. (defun prince-of-clarity (w)
  3220.   "Take a cons of two lists and make a list of conses.
  3221.    Think of this function as being like a zipper."
  3222.   (do ((y (car w) (cdr y))
  3223.        (z (cdr w) (cdr z))
  3224.        (x '() (cons (cons (car y) (car z)) x)))
  3225.       ((null y) x)
  3226.     (when (null z)
  3227.       (cerror "Will self-pair extraneous items"
  3228.               "Mismatch - gleep!   S" y)
  3229.       (setq z y))))
  3230.  
  3231. The prog construct may be explained in terms of the simpler constructs block,
  3232. let, and tagbody as follows:
  3233.  
  3234. (prog variable-list {declaration}* . body)
  3235.    == (block nil (let variable-list {declaration}* (tagbody . body)))
  3236.  
  3237. The prog* special form is almost the same as prog. The only difference is that
  3238. the binding and initialization of the temporary variables is done sequentially,
  3239. so that the init form for each one can use the values of previous ones.
  3240. Therefore prog* is to prog as let* is to let. For example,
  3241.  
  3242. (prog* ((y z) (x (car y)))
  3243.        (return x))
  3244.  
  3245. returns the car of the value of z.
  3246.  
  3247. [change_begin]
  3248. I haven't seen prog used very much in the last several years. Apparently
  3249. splitting it into functional constituents (let, block, tagbody) has been a
  3250. success. Common Lisp programmers now tend to use whichever specific construct
  3251. is appropriate.
  3252. [change_end]
  3253.  
  3254. [Special Form]
  3255. go tag
  3256.  
  3257. The (go tag) special form is used to do a ``go to'' within a tagbody construct.
  3258. The tag must be a symbol or an integer; the tag is not evaluated. go transfers
  3259. control to the point in the body labelled by a tag eql to the one given. If
  3260. there is no such tag in the body, the bodies of lexically containing tagbody
  3261. constructs (if any) are examined as well. It is an error if there is no
  3262. matching tag lexically visible to the point of the go.
  3263.  
  3264. The go form does not ever return a value.
  3265.  
  3266. As a matter of style, it is recommended that the user think twice before using
  3267. a go. Most purposes of go can be accomplished with one of the iteration
  3268. primitives, nested conditional forms, or return-from. If the use of go seems to
  3269. be unavoidable, perhaps the control structure implemented by go should be
  3270. packaged as a macro definition.
  3271.  
  3272. -------------------------------------------------------------------------------
  3273.  
  3274. 7.9. Structure Traversal and Side Effects
  3275.  
  3276. [change_begin]
  3277. X3J13 voted in January 1989 (MAPPING-DESTRUCTIVE-INTERACTION)   to restrict
  3278. side effects during the course of a built-in operation that can execute
  3279. user-supplied code while traversing a data structure.
  3280.  
  3281. Consider the following example:
  3282.  
  3283. (let ((x '(apples peaches pumpkin pie)))
  3284.   (dolist (z x)
  3285.     (when (eq z 'peaches)
  3286.       (setf (cddr x) '(mango kumquat)))
  3287.     (format t " S " (car z))))
  3288.  
  3289. Depending on the details of the implementation of dolist, this bit of code
  3290. could easily print
  3291.  
  3292. apples peaches mango kumquat
  3293.  
  3294. (which is perhaps what was intended), but it might as easily print
  3295.  
  3296. apples peaches pumpkin pie
  3297.  
  3298. Here is a plausible implementation of dolist that produces the first result:
  3299.  
  3300. (defmacro dolist ((var listform &optional (resultform ''nil))
  3301.                   &body body)
  3302.   (let ((tailvar (gensym "DOLIST")))
  3303.     `(do ((,tailvar ,listform (cdr ,tailvar)))
  3304.          ((null ,tailvar) ,resultform)
  3305.        (let ((,var (car ,tailvar))) ,@body))
  3306.  
  3307. But here is a plausible implementation of dolist that produces the second
  3308. result:
  3309.  
  3310. (defmacro dolist ((var listform &optional (resultform ''nil))
  3311.                   &body body)
  3312.   (let ((tailvar (gensym "DOLIST")))
  3313.     `(do ((,tailvar ,listform))
  3314.          ((null ,tailvar) ,resultform)
  3315.        (let ((,var (pop ,tailvar))) ,@body))
  3316.  
  3317. The X3J13 recognizes and legitimizes varying implementation practices: in
  3318. general it is an error for code executed during a ``structure-traversing''
  3319. operation to destructively modify the structure in a way that might affect the
  3320. ongoing traversal operation. The committee identified in particular the
  3321. following special cases.
  3322.  
  3323. For list traversal operations, the cdr chain may not be destructively modified.
  3324.  
  3325. For array traversal operations, the array may not be adjusted (see
  3326. adjust-array) and its fill pointer, if any, may not be modified.
  3327.  
  3328. For hash table operations (such as with-hash-table-iterator and maphash), new
  3329. entries may not be added or deleted, except that the very entry being processed
  3330. by user code may be changed or deleted.
  3331.  
  3332. For package symbol operations (for example, with-package-iterator and
  3333. do-symbols), new symbols may not be interned in, nor symbols uninterned from,
  3334. the packages being traversed or any packages they use, except that the very
  3335. symbol being processed by user code may be uninterned.
  3336.  
  3337. X3J13 noted that this vote is intended to clarify restrictions on the use of
  3338. structure traversal operations that are not themselves inherently destructive;
  3339. for example, it applies to map and dolist. Destructive operators such as delete
  3340. require even more complicated restrictions and are addressed by a separate
  3341. proposal.
  3342.  
  3343. The X3J13 vote did not specify a complete list of the operations to which these
  3344. restrictions apply. Table 7-1 shows what I believe to be a complete list of
  3345. operations that traverse structures and take user code as a body (in the case
  3346. of macros) or as a functional argument (in the case of functions).
  3347.  
  3348. In addition, note that user code should not modify list structure that might be
  3349. undergoing interpretation by the evaluator, whether explicitly invoked via eval
  3350. or implicitly invoked, for example as in the case of a hook function (a
  3351. defstruct print function, the value of *evalhook* or *applyhook*, etc.) that
  3352. happens to be a closure of interpreted code. Similarly, defstruct print
  3353. functions and other hooks should not perform side effects on data structures
  3354. being printed or being processed by format, or on a string given to
  3355. make-string-input-stream. You get the idea; be sensible.
  3356.  
  3357. Note that an operation such as mapcar or dolist traverses not only cdr pointers
  3358. (in order to chase down the list) but also car pointers (in order to obtain the
  3359. elements themselves). The restriction against modification appears to apply to
  3360. all these pointers.
  3361.  
  3362.  
  3363.  
  3364. Table 7-1: Structure Traversal Operations Subject to Side Effect Restrictions
  3365. -----------------------------------------------------------------------------
  3366. adjoin                   maphash                 reduce
  3367. assoc                    mapl                    remove
  3368. assoc-if                 maplist                 remove-duplicates
  3369. assoc-if-not             member                  remove-if
  3370. count                    member-if               remove-if-not
  3371. count-if                 member-if-not           search
  3372. count-if-not             merge                   set-difference
  3373. delete                   mismatch                set-exclusive-or
  3374. delete-duplicates        nintersection           some
  3375. delete-if                notany                  sort
  3376. delete-if-not            notevery                stable-sort
  3377. do-all-symbols           nset-difference         sublis
  3378. do-external-symbols      nset-exclusive-or       subsetp
  3379. do-symbols               nsublis                 subst
  3380. dolist                   nsubst                  subst-if
  3381. eval                     nsubst-if               subst-if-not
  3382. every                    nsubst-if-not           substitute
  3383. find                     nsubstitute             substitute-if
  3384. find-if                  nsubstitute-if          substitute-if-not
  3385. find-if-not              nsubstitute-if-not      tree-equal
  3386. intersection             nunion                  union
  3387. certain loop clauses     position                with-hash-table-iterator
  3388. map                      position-if             with-input-from-string
  3389. mapc                     position-if-not         with-output-to-string
  3390. mapcan                   rassoc                  with-package-iterator
  3391. mapcar                   rassoc-if
  3392. mapcon                   rassoc-if-not
  3393. -----------------------------------------------------------------------------
  3394.  
  3395. [change_end]
  3396.  
  3397. -------------------------------------------------------------------------------
  3398.  
  3399. 7.10. Multiple Values
  3400.  
  3401. Ordinarily the result of calling a Lisp function is a single Lisp object.
  3402. Sometimes, however, it is convenient for a function to compute several objects
  3403. and return them. Common Lisp provides a mechanism for handling multiple values
  3404. directly. This mechanism is cleaner and more efficient than the usual tricks
  3405. involving returning a list of results or stashing results in global variables.
  3406.  
  3407. -------------------------------------------------------------------------------
  3408.  
  3409.    *  Constructs for Handling Multiple Values
  3410.    *  Rules Governing the Passing of Multiple Values
  3411.  
  3412. -------------------------------------------------------------------------------
  3413.  
  3414. 7.10.1. Constructs for Handling Multiple Values
  3415.  
  3416. Normally multiple values are not used. Special forms are required both to
  3417. produce multiple values and to receive them. If the caller of a function does
  3418. not request multiple values, but the called function produces multiple values,
  3419. then the first value is given to the caller and all others are discarded; if
  3420. the called function produces zero values, then the caller gets nil as a value.
  3421.  
  3422. The primary primitive for producing multiple values is values, which takes any
  3423. number of arguments and returns that many values. If the last form in the body
  3424. of a function is a values with three arguments, then a call to that function
  3425. will return three values. Other special forms also produce multiple values, but
  3426. they can be described in terms of values. Some built-in Common Lisp functions,
  3427. such as floor, return multiple values; those that do are so documented.
  3428.  
  3429. The special forms and macros for receiving multiple values are as follows:
  3430.  
  3431. multiple-value-list
  3432. multiple-value-call
  3433. multiple-value-prog1
  3434. multiple-value-bind
  3435. multiple-value-setq
  3436.  
  3437. These specify a form to evaluate and an indication of where to put the values
  3438. returned by that form.
  3439.  
  3440. [Function]
  3441. values &rest args
  3442.  
  3443. All of the arguments are returned, in order, as values. For example:
  3444.  
  3445. (defun polar (x y)
  3446.   (values (sqrt (+ (* x x) (* y y))) (atan y x)))
  3447.  
  3448. (multiple-value-bind (r theta) (polar 3.0 4.0)
  3449.   (vector r theta))
  3450.    => #(5.0 0.9272952)
  3451.  
  3452. The expression (values) returns zero values. This is the standard idiom for
  3453. returning no values from a function.
  3454.  
  3455. Sometimes it is desirable to indicate explicitly that a function will return
  3456. exactly one value. For example, the function
  3457.  
  3458. (defun foo (x y)
  3459.   (floor (+ x y) y))
  3460.  
  3461. will return two values because floor returns two values. It may be that the
  3462. second value makes no sense, or that for efficiency reasons it is desired not
  3463. to compute the second value. The values function is the standard idiom for
  3464. indicating that only one value is to be returned, as shown in the following
  3465. example.
  3466.  
  3467. (defun foo (x y)
  3468.   (values (floor (+ x y) y)))
  3469.  
  3470. This works because values returns exactly one value for each of its argument
  3471. forms; as for any function call, if any argument form to values produces more
  3472. than one value, all but the first are discarded.
  3473.  
  3474. There is absolutely no way in Common Lisp for a caller to distinguish between
  3475. returning a single value in the ordinary manner and returning exactly one
  3476. ``multiple value.'' For example, the values returned by the expressions (+ 1 2)
  3477. and (values (+ 1 2)) are identical in every respect: the single value 3.
  3478.  
  3479. [Constant]
  3480. multiple-values-limit
  3481.  
  3482. The value of multiple-values-limit is a positive integer that is the upper
  3483. exclusive bound on the number of values that may be returned from a function.
  3484. This bound depends on the implementation but will not be smaller than 20.
  3485. (Implementors are encouraged to make this limit as large as practicable without
  3486. sacrificing performance.) See lambda-parameters-limit and call-arguments-limit.
  3487.  
  3488. [Function]
  3489. values-list list
  3490.  
  3491. All of the elements of list are returned as multiple values. For example:
  3492.  
  3493. (values-list (list a b c)) == (values a b c)
  3494.  
  3495. In general,
  3496.  
  3497. (values-list list) == (apply #'values list)
  3498.  
  3499. but values-list may be clearer or more efficient.
  3500.  
  3501. [Macro]
  3502. multiple-value-list form
  3503.  
  3504. multiple-value-list evaluates form and returns a list of the multiple values it
  3505. returned. For example:
  3506.  
  3507. (multiple-value-list (floor -3 4)) => (-1 1)
  3508.  
  3509. multiple-value-list and values-list are therefore inverses of each other.
  3510.  
  3511. [Special Form]
  3512. multiple-value-call function {form}*
  3513.  
  3514. multiple-value-call first evaluates function to obtain a function and then
  3515. evaluates all of the forms. All the values of the forms are gathered together
  3516. (not just one value from each) and are all given as arguments to the function.
  3517. The result of multiple-value-call is whatever is returned by the function. For
  3518. example:
  3519.  
  3520. (+ (floor 5 3) (floor 19 4))
  3521.    == (+ 1 4) => 5
  3522. (multiple-value-call #'+ (floor 5 3) (floor 19 4))
  3523.    == (+ 1 2 4 3) => 10
  3524. (multiple-value-list form) == (multiple-value-call #'list form)
  3525.  
  3526. [Special Form]
  3527. multiple-value-prog1 form {form}*
  3528.  
  3529. multiple-value-prog1 evaluates the first form and saves all the values produced
  3530. by that form. It then evaluates the other forms from left to right, discarding
  3531. their values. The values produced by the first form are returned by
  3532. multiple-value-prog1. See prog1, which always returns a single value.
  3533.  
  3534. [Macro]
  3535.  
  3536. multiple-value-bind ({var}*) values-form
  3537.                       {declaration}* {form}*
  3538.  
  3539. The values-form is evaluated, and each of the variables var is bound to the
  3540. respective value returned by that form. If there are more variables than values
  3541. returned, extra values of nil are given to the remaining variables. If there
  3542. are more values than variables, the excess values are simply discarded. The
  3543. variables are bound to the values over the execution of the forms, which make
  3544. up an implicit progn. For example:
  3545.  
  3546. (multiple-value-bind (x) (floor 5 3) (list x)) => (1)
  3547. (multiple-value-bind (x y) (floor 5 3) (list x y)) => (1 2)
  3548. (multiple-value-bind (x y z) (floor 5 3) (list x y z))
  3549.    => (1 2 nil)
  3550.  
  3551. [Macro]
  3552. multiple-value-setq variables form
  3553.  
  3554. The variables must be a list of variables. The form is evaluated, and the
  3555. variables are set (not bound) to the values returned by that form. If there are
  3556. more variables than values returned, extra values of nil are assigned to the
  3557. remaining variables. If there are more values than variables, the excess values
  3558. are simply discarded.
  3559.  
  3560. -------------------------------------------------------------------------------
  3561. Compatibility note: In Lisp Machine Lisp this is called multiple-value. The
  3562. added clarity of the name multiple-value-setq in Common Lisp was deemed worth
  3563. the incompatibility with Lisp Machine Lisp.
  3564. -------------------------------------------------------------------------------
  3565.  
  3566. multiple-value-setq always returns a single value, which is the first value
  3567. returned by form, or nil if form produces zero values.
  3568.  
  3569. [change_begin]
  3570. X3J13 voted in March 1989 (SYMBOL-MACROLET-SEMANTICS)   to specify that if any
  3571. var refers not to an ordinary variable but to a binding made by
  3572. symbol-macrolet, then that var is handled as if setq were used to assign the
  3573. appropriate value to it.
  3574.  
  3575. [Macro]
  3576. nth-value n form
  3577.  
  3578. X3J13 voted in January 1989 (NTH-VALUE)   to add a new macro named nth-value.
  3579. The argument forms n and form are both evaluated. The value of n must be a
  3580. non-negative integer, and the form may produce any number of values. The
  3581. integer n is used as a zero-based index into the list of values. Value n of the
  3582. form is returned as the single value of the nth-value form; nil is returned if
  3583. the form produces no more than n values.
  3584.  
  3585. As an example, mod could be defined as
  3586.  
  3587. (defun mod (number divisor)
  3588.   (nth-value 1 (floor number divisor)))
  3589.  
  3590. Value number 1 is the second value returned by floor, the first value being
  3591. value number 0.
  3592.  
  3593. One could define nth-value simply as
  3594.  
  3595. (defmacro nth-value (n form)
  3596.   `(nth ,n (multiple-value-list ,form)))
  3597.  
  3598. but the clever implementor will doubtless find an implementation technique for
  3599. nth-value that avoids constructing an intermediate list of all the values of
  3600. the form.
  3601. [change_end]
  3602.  
  3603. Common Lisp the Language, 2nd Edition BR>
  3604. -------------------------------------------------------------------------------
  3605.  
  3606. 7.10.2. Rules Governing the Passing of Multiple Values
  3607.  
  3608. It is often the case that the value of a special form or macro call is defined
  3609. to be the value of one of its subforms. For example, the value of a cond is the
  3610. value of the last form in the selected clause.
  3611.  
  3612. In most such cases, if the subform produces multiple values, then the original
  3613. form will also produce all of those values. This passing back of multiple
  3614. values of course has no effect unless eventually one of the special forms for
  3615. receiving multiple values is reached.
  3616.  
  3617. To be explicit, multiple values can result from a special form under precisely
  3618. these circumstances:
  3619.  
  3620. Evaluation and application
  3621.  
  3622.    *  eval returns multiple values if the form given it to evaluate produces
  3623.      multiple values.
  3624.  
  3625.    *  apply, funcall, and multiple-value-call pass back multiple values from
  3626.      the function applied or called.
  3627.  
  3628. Implicit progn contexts
  3629.  
  3630.    *  The special form progn passes back multiple values resulting from
  3631.      evaluation of the last subform. Other situations referred to as ``implicit
  3632.      progn,'' where several forms are evaluated and the results of all but the
  3633.      last form are discarded, also pass back multiple values from the last
  3634.      form. These situations include the body of a lambda-expression, in
  3635.      particular those constructed by defun, defmacro, and deftype. Also
  3636.      included are bodies of the constructs eval-when, progv, let, let*, when,
  3637.      unless, block, multiple-value-bind, and catch, as well as clauses in such
  3638.      conditional constructs as case, typecase, ecase, etypecase, ccase, and
  3639.      ctypecase.
  3640.  
  3641. [change_begin]
  3642. X3J13 has voted to add many new constructs to the language that contain
  3643. implicit progn contexts. I won't attempt to list them all here. Of particular
  3644. interest, however, is locally, which may be regarded as simply a version of
  3645. progn that permits declarations before its body. This provides a useful
  3646. building block for constructing macros that permit declarations (but not
  3647. documentation strings) before their bodies and pass back any multiple values
  3648. produced by the last sub-form of a body. (If a body can contain a documentation
  3649. string, most likely lambda is the correct building block to use.)
  3650. [change_end]
  3651.  
  3652. Conditional constructs
  3653.  
  3654.    *  if passes back multiple values from whichever subform is selected (the
  3655.      then form or the else form).
  3656.  
  3657.    *  and and or pass back multiple values from the last subform but not from
  3658.      subforms other than the last.
  3659.  
  3660.    *  cond passes back multiple values from the last subform of the implicit
  3661.      progn of the selected clause. If, however, the clause selected is a
  3662.      singleton clause, then only a single value (the non-nil predicate value)
  3663.      is returned. This is true even if the singleton clause is the last clause
  3664.      of the cond. It is not permitted to treat a final clause (x) as being the
  3665.      same as (t x) for this reason; the latter passes back multiple values from
  3666.      the form x.
  3667.  
  3668. Returning from a block
  3669.  
  3670.    *  The block construct passes back multiple values from its last subform
  3671.      when it exits normally. If return-from (or return) is used to terminate
  3672.      the block prematurely, then return-from passes back multiple values from
  3673.      its subform as the values of the terminated block. Other constructs that
  3674.      create implicit blocks, such as do, dolist, dotimes, prog, and prog*, also
  3675.      pass back multiple values specified by return-from (or return).
  3676.  
  3677.    *  do passes back multiple values from the last form of the exit clause,
  3678.      exactly as if the exit clause were a cond clause. Similarly, dolist and
  3679.      dotimes pass back multiple values from the resultform if that is executed.
  3680.      These situations are all examples of implicit uses of return-from.
  3681.  
  3682. Throwing out of a catch
  3683.  
  3684.    *  The catch construct returns multiple values if the result form in a throw
  3685.      exiting from such a catch produces multiple values.
  3686.  
  3687. Miscellaneous situations
  3688.  
  3689.    *  multiple-value-prog1 passes back multiple values from its first subform.
  3690.      However, prog1 always returns a single value.
  3691.  
  3692.    *  unwind-protect returns multiple values if the form it protects returns
  3693.      multiple values.
  3694.  
  3695.    *  the returns multiple values if the form it contains returns multiple
  3696.      values.
  3697.  
  3698. Among special forms that never pass back multiple values are prog1, prog2,
  3699. setq, and multiple-value-setq. The conventional way to force only one value to
  3700. be returned from a form x is to write (values x).
  3701.  
  3702. The most important rule about multiple values is: No matter how many values a
  3703. form produces, if the form is an argument form in a function call, then exactly
  3704. one value (the first one) is used.
  3705.  
  3706. For example, if you write (cons (floor x)), then cons will always receive
  3707. exactly one argument (which is of course an error), even though floor returns
  3708. two values. To pass both values from floor to cons, one must write something
  3709. like (multiple-value-call #'cons (floor x)). In an ordinary function call, each
  3710. argument form produces exactly one argument; if such a form returns zero
  3711. values, nil is used for the argument, and if more than one value, all but the
  3712. first are discarded. Similarly, conditional constructs such as if that test the
  3713. value of a form will use exactly one value, the first one, from that form and
  3714. discard the rest; such constructs will use nil as the test value if zero values
  3715. are returned.
  3716.  
  3717. -------------------------------------------------------------------------------
  3718.  
  3719. 7.11. Dynamic Non-Local Exits
  3720.  
  3721. Common Lisp provides a facility for exiting from a complex process in a
  3722. non-local, dynamically scoped manner. There are two classes of special forms
  3723. for this purpose, called catch forms and throw forms, or simply catches and
  3724. throws. A catch form evaluates some subforms in such a way that, if a throw
  3725. form is executed during such evaluation, the evaluation is aborted at that
  3726. point and the catch form immediately returns a value specified by the throw.
  3727. Unlike block and return (section 7.7), which allow for exiting a block form
  3728. from any point lexically within the body of the block, the catch/throw
  3729. mechanism works even if the throw form is not textually within the body of the
  3730. catch form. The throw need only occur within the extent (time span) of the
  3731. evaluation of the body of the catch. This is analogous to the distinction
  3732. between dynamically bound (special) variables and lexically bound (local)
  3733. variables.
  3734.  
  3735. [Special Form]
  3736. catch tag {form}*
  3737.  
  3738. The catch special form serves as a target for transfer of control by throw. The
  3739. form tag is evaluated first to produce an object that names the catch; it may
  3740. be any Lisp object. A catcher is then established with the object as the tag.
  3741. The forms are evaluated as an implicit progn, and the results of the last form
  3742. are returned, except that if during the evaluation of the forms a throw should
  3743. be executed such that the tag of the throw matches (is eq to) the tag of the
  3744. catch and the catcher is the most recent outstanding catcher with that tag,
  3745. then the evaluation of the forms is aborted and the results specified by the
  3746. throw are immediately returned from the catch expression. The catcher
  3747. established by the catch expression is disestablished just before the results
  3748. are returned.
  3749.  
  3750. The tag is used to match throws with catches. (catch 'foo form) will catch a
  3751. (throw 'foo form) but not a (throw 'bar form). It is an error if throw is done
  3752. when there is no suitable catch ready to catch it.
  3753.  
  3754. Catch tags are compared using eq, not eql; therefore numbers and characters
  3755. should not be used as catch tags.
  3756.  
  3757. -------------------------------------------------------------------------------
  3758. Compatibility note: The name catch comes from MacLisp, but the syntax of catch
  3759. in Common Lisp is different. The MacLisp syntax was (catch form tag), where the
  3760. tag was not evaluated.
  3761. -------------------------------------------------------------------------------
  3762.  
  3763.  
  3764. [Special Form]
  3765. unwind-protect protected-form {cleanup-form}*
  3766.  
  3767. Sometimes it is necessary to evaluate a form and make sure that certain side
  3768. effects take place after the form is evaluated; a typical example is
  3769.  
  3770. (progn (start-motor)
  3771.        (drill-hole)
  3772.        (stop-motor))
  3773.  
  3774. The non-local exit facility of Common Lisp creates a situation in which the
  3775. above code won't work, however: if drill-hole should do a throw to a catch that
  3776. is outside of the progn form (perhaps because the drill bit broke), then
  3777. (stop-motor) will never be evaluated (and the motor will presumably be left
  3778. running). This is particularly likely if drill-hole causes a Lisp error and the
  3779. user tells the error-handler to give up and abort the computation. (A possibly
  3780. more practical example might be
  3781.  
  3782. (prog2 (open-a-file)
  3783.        (process-file)
  3784.        (close-the-file))
  3785.  
  3786. where it is desired always to close the file when the computation is terminated
  3787. for whatever reason. This case is so important that Common Lisp provides the
  3788. special form with-open-file for this purpose.)
  3789.  
  3790. In order to allow the example hole-drilling program to work, it can be
  3791. rewritten using unwind-protect as follows:
  3792.  
  3793. ;; Stop the motor no matter what (even if it failed to start).
  3794.  
  3795. (unwind-protect
  3796.   (progn (start-motor)
  3797.          (drill-hole))
  3798.   (stop-motor))
  3799.  
  3800. If drill-hole does a throw that attempts to quit out of the unwind-protect,
  3801. then (stop-motor) will be executed.
  3802.  
  3803. This example assumes that it is correct to call stop-motor even if the motor
  3804. has not yet been started. Remember that an error or interrupt may cause an exit
  3805. even before any initialization forms have been executed. Any state restoration
  3806. code should operate correctly no matter where in the protected code an exit
  3807. occurred. For example, the following code is not correct:
  3808.  
  3809. (unwind-protect
  3810.   (progn (incf *access-count*)
  3811.          (perform-access))
  3812.   (decf *access-count*))
  3813.  
  3814. If an exit occurs before completion of the incf operation the decf operation
  3815. will be executed anyway, resulting in an incorrect value for *access-count*.
  3816. The correct way to code this is as follows:
  3817.  
  3818. (let ((old-count *access-count*))
  3819.   (unwind-protect
  3820.     (progn (incf *access-count*)
  3821.            (perform-access))
  3822.     (setq *access-count* old-count)))
  3823.  
  3824. As a general rule, unwind-protect guarantees to execute the cleanup-forms
  3825. before exiting, whether it terminates normally or is aborted by a throw of some
  3826. kind. (If, however, an exit occurs during execution of the cleanup-forms, no
  3827. special action is taken. The cleanup-forms of an unwind-protect are not
  3828. protected by that unwind-protect, though they may be protected if that
  3829. unwind-protect occurs within the protected form of another unwind-protect.)
  3830. unwind-protect returns whatever results from evaluation of the protected-form
  3831. and discards all the results from the cleanup-forms.
  3832.  
  3833. It should be emphasized that unwind-protect protects against all attempts to
  3834. exit from the protected form, including not only ``dynamic exit'' facilities
  3835. such as throw but also ``lexical exit'' facilities such as go and return-from.
  3836. Consider this situation:
  3837.  
  3838. (tagbody
  3839.   (let ((x 3))
  3840.     (unwind-protect
  3841.       (if (numberp x) (go out))
  3842.       (print x)))
  3843.  out
  3844.   ...)
  3845.  
  3846. When the go is executed, the call to print is executed first, and then the
  3847. transfer of control to the tag out is completed.
  3848.  
  3849. [change_begin]
  3850. X3J13 voted in March 1989 (EXIT-EXTENT)   to clarify the interaction of
  3851. unwind-protect with constructs that perform exits.
  3852.  
  3853. Let an exit be a point out of which control can be transferred. For a throw the
  3854. exit is the matching catch; for a return-from the exit is the corresponding
  3855. block. For a go the exit is the statement within the tagbody (the one to which
  3856. the target tag belongs) which is being executed at the time the go is
  3857. performed.
  3858.  
  3859. The extent of an exit is dynamic; it is not indefinite. The extent of an exit
  3860. begins when the corresponding form (catch, block, or tagbody statement) is
  3861. entered. When the extent of an exit has ended, it is no longer legal to return
  3862. from it.
  3863.  
  3864. Note that the extent of an exit is not the same thing as the scope or extent of
  3865. the designator by which the exit is identified. For example, a block name has
  3866. lexical scope but the extent of its exit is dynamic. The extent of a catch tag
  3867. could differ from the extent of the exit associated with the catch (which is
  3868. exactly what is at issue here). The difference matters when there are transfers
  3869. of control from the cleanup clauses of an unwind-protect.
  3870.  
  3871. When a transfer of control out of an exit is initiated by throw, return-from,
  3872. or go, a variety of events occur before the transfer of control is complete:
  3873.  
  3874.    *  The cleanup clauses of any intervening unwind-protect clauses are
  3875.      evaluated.
  3876.    *  Intervening dynamic bindings of special variables and catch tags are
  3877.      undone.
  3878.    *  Intervening exits are abandoned, that is, their extent ends and it is no
  3879.      longer legal to attempt to transfer control from them.
  3880.    *  The extent of the exit being invoked ends.
  3881.    *  Control is finally passed to the target.
  3882.  
  3883. The first edition left the order of these events in some doubt. The
  3884. implementation note for throw hinted that the first two processes are
  3885. interwoven, but it was unclear whether it is permissible for an implementation
  3886. to abandon all intervening exits before processing any intervening
  3887. unwind-protect cleanup clauses.
  3888.  
  3889. The clarification adopted by X3J13 is as follows. Intervening exits are
  3890. abandoned as soon as the transfer of control is initiated; in the case of a
  3891. throw, this occurs at the beginning of the ``second pass'' mentioned in the
  3892. implementation note. It is an error to attempt a transfer of control to an exit
  3893. whose dynamic extent has ended.
  3894.  
  3895. Next the evaluation of unwind-protect cleanup clauses and the undoing of
  3896. dynamic bindings and catch tags are performed together, in the order
  3897. corresponding to the reverse of the order in which they were established. The
  3898. effect of this is that the cleanup clauses of an unwind-protect will see the
  3899. same dynamic bindings of variables and catch tags as were visible when the
  3900. unwind-protect was entered. (However, some of those catch tags may not be
  3901. useable because they correspond to abandoned exit points.)
  3902.  
  3903. Finally control is transferred to the originally invoked exit and
  3904. simultaneously that exit is abandoned.
  3905.  
  3906. The effect of this specification is that once a program has attempted to
  3907. transfer control to a particular exit, an unwind-protect cleanup form cannot
  3908. step in and decide to transfer control to a more recent (nested) exit, blithely
  3909. forgetting the original exit request. However, a cleanup form may restate the
  3910. request to transfer to the same exit that started the cleanup process.
  3911.  
  3912. Here is an example based on a nautical metaphor. The function gently moves an
  3913. oar in the water with low force, but if an oar gets stuck, the caller will
  3914. catch a crab. The function row takes a boat, an oar-stroking function, a
  3915. stream, and a count; an oar is constructed for the boat and stream and the
  3916. oar-stroking function is called :count times. The function life rows a
  3917. particular boat. Merriment follows, except that if the oarsman is winded he
  3918. must stop to catch his breath.
  3919.  
  3920. (defun gently (oar)
  3921.   (stroke oar :force 0.5)
  3922.   (when (stuck oar)
  3923.     (throw 'crab nil)))
  3924.  
  3925. (defun row (boat stroke-fn stream &key count)
  3926.   (let ((oar (make-oar boat stream)))
  3927.     (loop repeat count do (funcall stroke-fn oar))))
  3928.  
  3929. (defun life ()
  3930.   (catch 'crab
  3931.     (catch 'breath
  3932.       (unwind-protect
  3933.         (row *your-boat* #'gently *query-io* :count 3))
  3934.         (when (winded) (throw 'breath nil)))
  3935.       (loop repeat 4 (set-mode :merry))
  3936.       (dream))))
  3937.  
  3938. Suppose that the oar gets stuck, causing gently to call throw with the tag
  3939. crab. The program is then committed to exiting from the outer catch (the one
  3940. with the tag crab). As control breaks out of the unwind-protect form, the
  3941. winded test is executed. Suppose it is true; then another call to throw occurs,
  3942. this time with the tag breath. The inner catch (the one with the tag breath)
  3943. has been abandoned as a result of the first throw operation (still in
  3944. progress). The clarification voted by X3J13 specifies that the program is in
  3945. error for attempting to transfer control to an abandoned exit point. To put it
  3946. in terms of the example: once you have begun to catch a crab, you cannot rely
  3947. on being able to catch your breath.
  3948.  
  3949. Implementations may support longer extents for exits than is required by this
  3950. specification, but portable programs may not rely on such extended extents.
  3951.  
  3952. (This specification is somewhat controversial. An alternative proposal was that
  3953. the abandoning of exits should be lumped in with the evaluation of
  3954. unwind-protect cleanup clauses and the undoing of dynamic bindings and catch
  3955. tags, performing all in reverse order of establishment. X3J13 agreed that this
  3956. approach is theoretically cleaner and more elegant but also more stringent and
  3957. of little additional practical use. There was some concern that a more
  3958. stringent specification might be a great added burden to some implementors and
  3959. would achieve only a small gain for users.)
  3960. [change_end]
  3961.  
  3962. [Special Form]
  3963. throw tag result
  3964.  
  3965. The throw special form transfers control to a matching catch construct. The tag
  3966. is evaluated first to produce an object called the throw tag; then the result
  3967. form is evaluated, and its results are saved (if the result form produces
  3968. multiple values, then all the values are saved). The most recent outstanding
  3969. catch whose tag matches the throw tag is exited; the saved results are returned
  3970. as the value(s) of the catch. A catch matches only if the catch tag is eq to
  3971. the throw tag.
  3972.  
  3973. In the process, dynamic variable bindings are undone back to the point of the
  3974. catch, and any intervening unwind-protect cleanup code is executed. The result
  3975. form is evaluated before the unwinding process commences, and whatever results
  3976. it produces are returned from the catch.
  3977.  
  3978. If there is no outstanding catcher whose tag matches the throw tag, no
  3979. unwinding of the stack is performed, and an error is signalled. When the error
  3980. is signalled, the outstanding catchers and the dynamic variable bindings are
  3981. those in force at the point of the throw.
  3982.  
  3983. -------------------------------------------------------------------------------
  3984. Implementation note: These requirements imply that throwing should typically
  3985. make two passes over the control stack. In the first pass it simply searches
  3986. for a matching catch. In this search every catch must be considered, but every
  3987. unwind-protect should be ignored. On the second pass the stack is actually
  3988. unwound, one frame at a time, undoing dynamic bindings and outstanding
  3989. unwind-protect constructs in reverse order of creation until the matching catch
  3990. is reached.
  3991. -------------------------------------------------------------------------------
  3992. Compatibility note: The name throw comes from MacLisp, but the syntax of throw
  3993. in Common Lisp is different. The MacLisp syntax was (throw form tag), where the
  3994. tag was not evaluated.
  3995. -------------------------------------------------------------------------------
  3996.  
  3997.  
  3998.  
  3999.  
  4000.  
  4001.  
  4002.  
  4003.  
  4004.  
  4005.  
  4006.  
  4007.